Laravel 13 introduced first-party JSON:API Resources, a dedicated resource class that produces responses compliant with the JSON:API specification. This means you no longer need third-party packages to build standards-compliant APIs with Laravel.
Key Features
The built-in JsonApiResource handles the heavy lifting automatically:
Resource Object Serialization: Automatically structures your data with id, type, and attributes.
Relationship Inclusion: Supports the ?include= query parameter to load related resources (like author or comments).
Sparse Fieldsets: Allows clients to request specific fields via ?fields[posts]=title,body.
Compliant Headers: Automatically sets the Content-Type: application/vnd.api+json header.
Example: Generating and Using a Resource
You can generate a JSON:API resource using the make:resource command with the --json-api flag:
php artisan make:resource PostResource --json-api
The generated class extends JsonApiResource and allows you to define attributes and relationships simply:
use IlluminateHttpResourcesJsonApiJsonApiResource;
class PostResource extends JsonApiResource
{
public $attributes = [
notitle ,
body ,
created_at ,
];public $relationships = [
author ,
comments ,
];
}
You can then return it from a route just like a standard resource:
Route::get( /api/posts/{post} , function (Post $post) {
return new PostResource($post);
});
This will output a correctly formatted JSON:API response, including the data object with the resource is id, type, and attributes.