Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 67 ยท APIs

API Design: Errors, Pagination, Filtering and Versioning

Design a Laravel API clients enjoy - consistent JSON errors, exception rendering, cursor pagination, safe filtering and sorting, rate limits, versioning and OpenAPI.

Returning JSON is the easy half of an API. The hard half is everything around it: what an error looks like, how a client walks through 10 million rows, how it asks for "published posts, newest first", and how you change the API next year without breaking apps that are already installed on people's phones. These are design decisions, and the best time to make them is before the first client exists.

This lesson builds on API resources. You will make errors consistent, learn offset and cursor pagination, add filtering and sorting with a whitelist, protect the API with rate limits, and plan versions and documentation. Laravel code is read-only; the runnable examples are plain-PHP stand-ins on SQLite. For the language-agnostic side, see versioning and OpenAPI in PHP and REST APIs.

One shape for every error

Clients write code against your errors, so every failure should look the same. Laravel already gives you a convention for validation errors (status 422):

JSON
{
  "message": "The title field is required.",
  "errors": { "title": ["The title field is required."] }
}

Reuse that message key for every other error: 401, 403, 404, 429 and 500 should all return JSON with a message. Two settings make Laravel do this reliably.

First, make sure API requests are always treated as JSON requests, even when a client forgets Accept: application/json. In bootstrap/app.php:

PHP
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

->withExceptions(function (Exceptions $exceptions): void {
    $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
        return $request->is('api/*') || $request->expectsJson();
    });

    $exceptions->render(function (NotFoundHttpException $e, Request $request) {
        if ($request->is('api/*')) {
            return response()->json(['message' => 'Resource not found.'], 404);
        }
    });
})

Second, never leak internals. With APP_DEBUG=false an uncaught exception becomes {"message": "Server Error"} with status 500, with no stack trace. Keep debug off everywhere except your own machine, and log the real error (logging and errors).

Use the status codes from the previous lesson, and add a machine-readable code only if clients need to branch on it, for example "code": "subscription_expired". Human text can change; codes should not.

Pagination: offset versus cursor

Offset pagination (paginate()) uses LIMIT 15 OFFSET 30. It is simple and gives page numbers and a total, but it has two weaknesses: the database still walks past all skipped rows (page 10,000 is slow), and if rows are inserted while a client is paging, items shift and the client sees duplicates or gaps.

Cursor pagination (cursorPaginate()) remembers the last row seen and asks for rows after it: WHERE id > 120 ORDER BY id LIMIT 15. It uses an index, stays fast on huge tables, and is stable under inserts. The price: no page numbers and no jumping to page 7.

PHP
// offset: page numbers and totals
return PostResource::collection(Post::orderBy('id')->paginate(15));

// cursor: next/prev cursors, much better for feeds and big tables
return PostResource::collection(Post::orderBy('id')->cursorPaginate(15));
// GET /api/posts?cursor=eyJpZCI6MTIwLCJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9

The cursor is an opaque, encoded string: clients must pass it back unchanged and never build it themselves. Cursor pagination needs a stable, unique orderBy (add id as a tiebreaker when you sort by a non-unique column).

flowchart LR
    A["Page 1<br/>ids 1..15"] -- "cursor after id 15" --> B["Page 2<br/>ids 16..30"]
    B -- "cursor after id 30" --> C["Page 3<br/>ids 31..45"]

Each cursor encodes where the previous page ended, so no rows are skipped or repeated.

Filtering and sorting safely

Clients want GET /api/posts?status=published&sort=-created_at. The dangerous way is to feed query-string keys straight into where() and orderBy(): a client could then sort by a private column or probe your schema. The safe way is a whitelist.

PHP
public function index(Request $request)
{
    $request->validate([
        'status' => ['nullable', 'in:draft,published'],
        'sort' => ['nullable', 'in:created_at,-created_at,title,-title'],
        'per_page' => ['nullable', 'integer', 'between:1,100'],
    ]);

    $query = Post::query()
        ->when($request->status, fn ($q, $status) => $q->where('status', $status));

    if ($sort = $request->string('sort')->toString()) {
        $direction = str_starts_with($sort, '-') ? 'desc' : 'asc';
        $query->orderBy(ltrim($sort, '-'), $direction);
    }

    return PostResource::collection(
        $query->orderBy('id')->paginate($request->integer('per_page', 15))
    );
}

Cap per_page: a client asking for per_page=1000000 is a denial-of-service attack in one parameter. Packages such as Spatie's Laravel Query Builder add a full filter/sort/include syntax if your API grows, but the whitelist idea stays the same.

The stand-in below does the same in plain PHP and SQLite: a whitelist of filters and sort columns, a capped page size, and bound values.

PHP Whitelisted filtering, sorting and capped pagination

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.

The third call shows the defense: secret is not in the sort whitelist, so the default order is used, and per_page=1000 is quietly reduced to 5.

Cursor pagination, in miniature

Here is the idea behind a cursor as plain code: the cursor is an encoded "last seen id", and the next page is "everything after it".

PHP A cursor paginator and a JSON error envelope

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.

Laravel's real cursor also stores which columns you ordered by, and signs nothing: treat it as opaque, not secret.

Rate limiting

Protect every public API with the throttle middleware and a named limiter, usually keyed by user id and falling back to IP (caching):

PHP
RateLimiter::for('api', function (Request $request) {
    return $request->user()
        ? Limit::perMinute(120)->by($request->user()->id)
        : Limit::perMinute(30)->by($request->ip());
});

Throttled responses are 429 with Retry-After and X-RateLimit-* headers, so well-behaved clients can slow down. Give expensive endpoints (search, exports, login) their own tighter limiter.

Versioning

Once clients depend on your JSON, changing a field is a breaking change. Adding a new optional field is usually safe; renaming, removing or changing the type of a field is not. A version in the URL is the simplest scheme, and Laravel lets you set the prefix once in bootstrap/app.php:

PHP
->withRouting(
    web: __DIR__.'/../routes/web.php',
    api: __DIR__.'/../routes/api.php',
    apiPrefix: 'api/v1',
)

Or group versions yourself:

PHP
Route::prefix('v1')->group(base_path('routes/api_v1.php'));
Route::prefix('v2')->group(base_path('routes/api_v2.php'));

Put each version's controllers and resources in their own namespace (App\Http\Controllers\Api\V1, App\Http\Resources\V1) so that V2 can differ without touching V1. Share logic through services and actions, not by copying controllers (architecture patterns). When you retire a version, announce a date and send a Deprecation or Sunset header first.

Documenting with OpenAPI

An OpenAPI document describes your endpoints, parameters and responses in a standard format that tools turn into interactive docs and client SDKs. Packages such as Scramble can generate it from your routes, form requests and resources, and Scribe or L5-Swagger take other approaches. Whichever you choose, generate the document in CI so it never drifts from the code, and treat a changed document in a pull request as a review signal for API changes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is cursor pagination better than offset pagination for a huge, busy table?

    A cursor continues after the last seen row, so the database does not skip over many rows and the client does not see duplicates when new rows arrive.
  2. 2. What is the safest way to support ?sort=title in an API?

    A whitelist prevents clients from sorting by private columns or injecting unexpected input into the query.
  3. 3. Which change is NOT considered breaking for existing API clients?

    Existing clients ignore fields they do not know, so adding an optional field is normally safe. Renaming, removing or retyping fields breaks them.
  4. 4. Why should unexpected exceptions return only a generic message in an API?

    Internal details help attackers. Return a generic message with a 500 status and log the details on the server instead.
  5. 5. What should an API do when a client asks for per_page=1000000?

    An uncapped page size lets one request load enormous amounts of data, so validate or clamp it.

Summary

  • Give every error the same JSON shape with a message; force JSON rendering for api/* and never leak internals.
  • Use paginate() for small, page-numbered lists and cursorPaginate() for feeds and large tables.
  • Filter and sort through whitelists and cap per_page.
  • Rate limit with named limiters and expect 429 plus Retry-After.
  • Version in the URL (api/v1), keep versions in separate namespaces and deprecate with notice.
  • Generate OpenAPI documentation from code and keep it in CI.

Next: The HTTP Client and Consuming APIs