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., 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.