Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 67 ยท APIs

Building JSON APIs with API Resources in Laravel

Build a JSON API in Laravel with install:api, apiResource routes and JsonResource classes, including collections, conditional fields, pagination and HTTP status codes.

A mobile app, a JavaScript front end or another company's server often needs your data as JSON instead of HTML. Laravel makes this easy: return an array or an Eloquent model from a route and it becomes JSON automatically. That shortcut is fine for a prototype, but it has a problem. A model turns into JSON with every column it has, so a new database column silently becomes a new public API field, and the database layout becomes your API contract.

API resources solve this. A resource is a small class that describes exactly how one model is turned into JSON: which fields, with which names and formats. In this lesson you will set up API routes, write resources and collections, hide or show fields conditionally, return paginated lists, and choose correct HTTP status codes. Laravel code is shown read-only; the runnable examples are a plain-PHP stand-in so you can see the transformation step by step. For API basics outside Laravel, see REST APIs in PHP.

Setting up API routes

New Laravel apps do not include API routes by default. One command adds them:

Terminal
php artisan install:api

It creates routes/api.php, registers it in bootstrap/app.php (every route gets the /api prefix and the api middleware group, with no session and no CSRF), and installs Laravel Sanctum for token authentication (API authentication with Sanctum). Then define routes:

PHP
// routes/api.php
use App\Http\Controllers\Api\PostController;
use Illuminate\Support\Facades\Route;

Route::apiResource('posts', PostController::class);

apiResource registers the five JSON-friendly routes (index, store, show, update, destroy) and leaves out the HTML-form routes create and edit. See php artisan route:list for the result: GET /api/posts, POST /api/posts, GET /api/posts/{post}, and so on.

Your first resource

Terminal
php artisan make:resource PostResource
PHP
namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'excerpt' => str($this->body)->limit(120)->toString(),
            'published_at' => $this->published_at?->toIso8601String(),
        ];
    }
}

Inside toArray(), $this is the model: you read properties directly. Use it in a controller:

PHP
class PostController extends Controller
{
    public function index()
    {
        return PostResource::collection(Post::latest()->paginate(15));
    }

    public function show(Post $post)
    {
        return new PostResource($post);     // or PostResource::make($post)
    }
}
flowchart LR
    M["Eloquent model<br/>(all columns)"] --> R["PostResource::toArray()<br/>(your public shape)"]
    R --> W["Wrapped in 'data'"]
    W --> J["JSON response"]

A resource sits between the model and the response, so the database shape and the API shape can change independently.

By default the JSON is wrapped in a data key:

JSON
{ "data": { "id": 1, "title": "Hello", "slug": "hello", "excerpt": "...", "published_at": null } }

Wrapping leaves room for links and meta next to the data. If you prefer plain output, call JsonResource::withoutWrapping() in AppServiceProvider::boot(). Pick one convention and keep it for the whole API.

Relationships and conditional fields

Do not put a field in a resource if you do not always want to send it. Laravel's conditional helpers add keys only when a condition is true:

PHP
public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'title' => $this->title,

        // only when the relationship was already loaded (prevents N+1 queries)
        'author' => UserResource::make($this->whenLoaded('author')),
        'comments' => CommentResource::collection($this->whenLoaded('comments')),

        // only when withCount('comments') was used
        'comments_count' => $this->whenCounted('comments'),

        // only for admins
        'internal_notes' => $this->when($request->user()?->isAdmin(), $this->internal_notes),

        // several keys at once
        $this->mergeWhen($this->isPublished(), [
            'published_at' => $this->published_at->toIso8601String(),
            'url' => route('posts.show', $this),
        ]),
    ];
}

whenLoaded() is especially important. It never triggers a query: if you forgot with('author') the key is simply missing instead of silently causing one query per row (eager loading and N+1). Load what you need in the controller: Post::with('author')->paginate(15).

What the resource does, step by step

The stand-in below is a tiny JsonResource with when(), whenLoaded(), wrapping and a collection, so you can watch the transformation without a framework.

PHP A resource transformer with conditional fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that secret_column and the author's password never appear: only fields named in toArray() get out. That whitelist is the main safety benefit of resources.

Collections and pagination

PostResource::collection($posts) applies the resource to each item. When you pass a paginator (paginate() or simplePaginate()), Laravel adds pagination details automatically:

JSON
{
  "data": [ { "id": 1, "title": "Hello" } ],
  "links": { "first": "/api/posts?page=1", "last": "/api/posts?page=4", "prev": null, "next": "/api/posts?page=2" },
  "meta": { "current_page": 1, "per_page": 15, "total": 52, "last_page": 4 }
}

The meta block also lists the page links and other details; the exact keys depend on the version, so read a real response rather than hard-coding assumptions. Clients follow links.next until it is null. For huge tables prefer cursor pagination, covered in API design and versioning.

If a collection needs extra data (for example totals), generate a dedicated class with php artisan make:resource PostCollection --collection and add a with() method or toArray() override.

Status codes

An API speaks through HTTP status codes as much as through JSON. Use the right one:

Situation Status In Laravel
Successful read or update 200 OK return a resource
Created a record 201 Created return new PostResource($post) after create(); Laravel sets 201 for a model that was just created
Deleted, nothing to return 204 No Content return response()->noContent();
Validation failed 422 Unprocessable Content automatic from $request->validate() or a form request
Not logged in 401 Unauthorized auth:sanctum middleware
Logged in but not allowed 403 Forbidden policies and gates
Missing record 404 Not Found route model binding fails automatically
Too many requests 429 throttle middleware

You can set the code yourself on any resource response:

PHP
public function store(StorePostRequest $request)
{
    $post = $request->user()->posts()->create($request->validated());

    return (new PostResource($post))
        ->response()
        ->setStatusCode(201)
        ->header('Location', route('posts.show', $post));
}

Clients should send Accept: application/json. With that header Laravel answers validation errors and missing models in JSON; without it, a browser-style request may be redirected to an HTML page instead (validation).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does php artisan install:api do?

    install:api adds the API routes file, registers it with the api middleware group and the /api prefix, and sets up Sanctum for token authentication.
  2. 2. Why return a resource instead of a model directly?

    A model serializes all its visible attributes. A resource is a whitelist that decouples the public API from the database schema.
  3. 3. What does $this->whenLoaded('author') do inside a resource?

    whenLoaded never queries. It includes the relationship data only when it was eager loaded, which avoids hidden N+1 queries.
  4. 4. A POST request creates a record successfully. Which status code fits best?

    201 Created tells the client a new resource exists. Returning a resource for a just-created model gives 201 automatically.
  5. 5. What does a paginated resource collection add next to the data key?

    When you pass a paginator to Resource::collection(), Laravel adds links (first, last, prev, next) and meta (page numbers and totals).

Summary

  • php artisan install:api adds routes/api.php (prefix /api, no session or CSRF) and Sanctum.
  • Route::apiResource() registers the five JSON routes.
  • A JsonResource turns a model into an explicit, whitelisted array, wrapped in data by default.
  • Use when(), whenLoaded(), whenCounted() and mergeWhen() for conditional fields.
  • Pass a paginator to Resource::collection() to get links and meta.
  • Return meaningful status codes: 201, 204, 401, 403, 404, 422, 429.

Next: API Design: Errors, Pagination, Filtering and Versioning