4,000 emails/month for free | Mailtrap sends real emails now!

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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
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 $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
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 →
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article