Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 16, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 16, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 16, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 16, 2025

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025

      Minecraft licensing robbed us of this controversial NFL schedule release video

      May 16, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The power of generators

      May 16, 2025
      Recent

      The power of generators

      May 16, 2025

      Simplify Factory Associations with Laravel’s UseFactory Attribute

      May 16, 2025

      This Week in Laravel: React Native, PhpStorm Junie, and more

      May 16, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025
      Recent

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Automated API documentation of Laravel API resources

    Automated API documentation of Laravel API resources

    December 20, 2024

    Automated API documentation of Laravel API resources

    API resources are an excellent way to build APIs with Laravel. They provide a transformation layer for models and the JSON returned by the API. And while you can configure how your models are represented as arrays, API resources provide a ton of tool to make that transformation more granular.

    Scramble is an automatic documentation generator for Laravel that creates API documentation without requiring PHPDoc annotations and has a first-party API resources support: scramble.dedoc.co.

    With its latest update, Scramble now supports all API resource’s payload-building methods, making automatically generated documentation even more accurate.

    Usage of API resources

    Let’s say we want to return a user model via an API. We can create the following API resource:

    <?php
    
    namespace AppHttpResources;
    
    use IlluminateHttpRequest;
    use IlluminateHttpResourcesJsonJsonResource;
    
    class UserResource extends JsonResource
    {
        public function toArray(Request $request): array
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'email' => $this->email,
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ];
        }
    }
    

    In the controller, we return the resource instance by passing the user model to its constructor:

    public function show(User $user)
    {
    return new UserResource($user);
    }
    

    While the resources may seem simple on the surface, they are actually quite comprehensive. There are many useful methods for building the API representation of a model: some allow you to merge data into the resulting array (e.g., merge, mergeWhen), while others, like whenLoaded, let you include a relation only if it is loaded—helping you avoid the N+1 issue.

    Scramble automatic documentation

    Scramble is OpenAPI (Swagger) documentation generator for Laravel. It generates API documentation for your project automatically without requiring you to manually write PHPDoc annotations.

    This ensures your documentation stays up-to-date, so you can rely on it with confidence.

    You can install Scramble via composer:

    composer require dedoc/scramble
    

    After installing Scramble, you can view the documentation for our example endpoint (assuming it is located at /api/user/{user} and you have not modified the default configuration):


    Without any annotations, Scramble has already documented the response type.

    Now, let’s enhance the API resource by adding more features. For instance, we might want to display the email attribute only when the authenticated user is an admin.

        public function toArray(Request $request): array
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
    -           'email' => $this->email,
    +           $this->mergeWhen($request->user()->is_admin, [
    +               /** @format email */
    +               'email' => $this->email,
    +           ]),
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ];
        }
    

    Scramble will now document the resource as follows, correctly identifying that the email attribute might not be included in the response (notice that email is no longer marked as required):


    A wide range of methods, such as when, are available through the ConditionallyLoadsAttributes trait used in JsonResource. In the latest update, Scramble now supports all of them.

    For instance, the attributes method allows you to merge multiple model attributes into the resulting array:

        public function toArray(Request $request): array
        {
            return [
    -           'id' => $this->id,
    -           'name' => $this->name,
    +           $this->attributes(['id', 'name']),
                $this->mergeWhen($request->user()->is_admin, [
                    /** @format email */
                    'email' => $this->email,
                ]),
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ];
        }
    

    API resources collections

    You can also return collections of API resources from your API. For example, when returning a list of users, you can implement it as follows:

    public function index()
    {
        return UserResource::collection(User::all());
    }
    

    Documenting resources collections

    Scramble supports both anonymous and named collections out of the box.

    Here is a generated documentation for the example above:


    If you add additional data to the collection, Scramble will document it automatically:

    public function index()
    {
        return UserResource::collection($users = User::all())->additional([
            /** The total count of users */
            'count' => (int) $users->count(),
        ]);
    }
    

    Here’s the resulting documentation:

    Modifying the resource response

    Another awesome feature of API resources is an ability to modify the response that is going to be returned from the API endpoint. This is done via modifying the response object in withResponse method in the API resource:

    public function withResponse(Request $request, JsonResponse $response)
    {
        $response->setStatusCode(201);
    }
    

    Documented modified resource

    Scramble supports withResponse documentation without any additional annotations. The example from above will be documented like the following:


    Notice the response status is 201, as defined in the withResponse status.


    API resources are an invaluable tool for Laravel developers. They allow you to prepare models for API responses with a powerful transformation layer.

    Scramble will take care of automatic up-to-date documentation of your API by understanding API resources really well without requiring you to write PHPDoc annotations.

    If you are not using Scramble yet, give it a go: https://scramble.dedoc.co

    Here is a demo documentation by Scramble: https://scramble.dedoc.co/demo/scramble


    The post Automated API documentation of Laravel API resources appeared first on Laravel News.

    Join the Laravel Newsletter to get all the latest
    Laravel articles like this directly in your inbox.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleCustomizing Data Transformations with Laravel Casts
    Next Article Announcing Inertia 2.0: Redefining Frontend Development for Laravel

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 17, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2024-47893 – VMware GPU Firmware Memory Disclosure

    May 17, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    How to Perform MS SQL Server Restore with RECOVERY and NORECOVERY Options

    Development

    Artificial intelligence enhances air mobility planning

    Artificial Intelligence

    Revolutionizing Financial Marketing with Artificial Intelligence (AI)

    Artificial Intelligence

    CodeSOD: Do a Flip

    Development

    Highlights

    Design System: Lessons Learned

    June 6, 2024

    None of their products were visually consistent. You could easily see 4 different eras of…

    The Rising Challenge of Third-Party Risks: Why CFOs Must Take Charge

    August 8, 2024

    Microsoft has filed a gaming patent for “crafting and altering game narratives” using generative AI

    January 13, 2025

    Python & Selenium: Finding and activating a dropdown list, then selecting a list item

    May 10, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.