Join the Mastering Laravel community to level up your skills and get trusted advice

Automated API documentation of Laravel API resources

Last updated on by

Automated API documentation of Laravel API resources image

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 App\Http\Resources;
 
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
 
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., mergemergeWhen), 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

Roman Lytvynenko photo

Working on https://scramble.dedoc.co – Modern Laravel OpenAPI (Swagger) documentation generator.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Auto-translate Application Strings with Laratext image

Auto-translate Application Strings with Laratext

Read article
Simplify Factory Associations with Laravel's UseFactory Attribute image

Simplify Factory Associations with Laravel's UseFactory Attribute

Read article
Improved Installation and Frontend Hooks in Laravel Echo 2.1 image

Improved Installation and Frontend Hooks in Laravel Echo 2.1

Read article
Filter Model Attributes with Laravel's New except() Method image

Filter Model Attributes with Laravel's New except() Method

Read article
Arr::from() Method in Laravel 12.14 image

Arr::from() Method in Laravel 12.14

Read article
Streamline API Resources with Laravel's Fluent Methods image

Streamline API Resources with Laravel's Fluent Methods

Read article