Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 67 ยท Projects

Project: A REST API with Sanctum

Build a versioned, token-protected bookmarks API in Laravel 13 with Sanctum, API resources, validation, rate limiting and Pest feature tests, step by step.

In this project you build the backend of a small bookmark manager: a JSON API where a client (a mobile app, a browser extension, a script) signs in, receives a token, and then creates and lists its own bookmarks. It pulls together a lot of earlier lessons: API resources, Sanctum tokens, form requests, API design and HTTP tests.

Laravel cannot run on this site, so the Laravel code below is read-only: copy it into a project of your own (a fresh laravel new app is enough). The runnable examples are plain PHP stand-ins that behave like the finished API, so you can see requests, status codes and JSON bodies without a server. Each section says which is which.

What you will build

The API has these endpoints, all under a v1 prefix so you can ship a v2 later without breaking old clients:

Method and path Needs Result
POST /api/v1/tokens email and password 201 with a new token
GET /api/v1/bookmarks token with bookmarks:read 200, paginated list of your bookmarks
POST /api/v1/bookmarks token with bookmarks:write 201, the new bookmark
GET /api/v1/bookmarks/{id} token with bookmarks:read 200, or 404 if it is not yours
DELETE /api/v1/tokens/current any valid token 204, the token is revoked
flowchart LR
    C["Client<br/>Authorization: Bearer token"] --> T["throttle:api"]
    T --> A["auth:sanctum"]
    A --> R["Route<br/>/api/v1/bookmarks"]
    R --> V["Form request<br/>validation"]
    V --> K["Controller"]
    K --> S["BookmarkResource<br/>JSON"]
    S --> C

Every request passes the rate limiter and authentication before it reaches validation, the controller and the resource that shapes the JSON.

Step 1: install the API scaffolding

Terminal
laravel new bookmarks-api
cd bookmarks-api
php artisan install:api
php artisan make:model Bookmark --migration --factory

install:api installs Laravel Sanctum, creates routes/api.php, publishes the personal_access_tokens migration and registers the API routes in bootstrap/app.php. Routes in routes/api.php get the /api URL prefix automatically and run without sessions or CSRF checks, which is what token clients need. Add the HasApiTokens trait to App\Models\User:

PHP
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Then describe the bookmarks table in the migration and run php artisan migrate:

PHP
Schema::create('bookmarks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title', 120);
    $table->string('url', 2048);
    $table->timestamps();

    $table->index(['user_id', 'id']);
});

The index on user_id and id matters: every query in this API filters by owner and orders by id. In the model, list the fields clients may set and nothing else:

PHP
class Bookmark extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'url'];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

user_id is deliberately not fillable. The owner always comes from the token, never from the request body, so a client cannot create bookmarks for somebody else (mass assignment at work).

Step 2: versioned routes

PHP
<?php

use App\Http\Controllers\Api\V1\BookmarkController;
use App\Http\Controllers\Api\V1\TokenController;
use Illuminate\Support\Facades\Route;

Route::prefix('v1')->name('v1.')->group(function () {
    Route::post('tokens', [TokenController::class, 'store'])
        ->middleware('throttle:5,1')
        ->name('tokens.store');

    Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
        Route::delete('tokens/current', [TokenController::class, 'destroy'])
            ->name('tokens.destroy');

        Route::apiResource('bookmarks', BookmarkController::class)
            ->only(['index', 'store', 'show']);
    });
});

apiResource registers the five resource routes without the HTML-form ones (create, edit); ->only() trims them to the three we need. Controllers live in App\Http\Controllers\Api\V1 so a future V2 namespace can sit beside them. The login route has its own, much stricter limit (5 attempts a minute per IP) because it is the one place where someone can guess passwords.

Step 3: issuing and revoking tokens

PHP
<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class TokenController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
            'device_name' => ['required', 'string', 'max:100'],
        ]);

        $user = User::where('email', $data['email'])->first();

        if (! $user || ! Hash::check($data['password'], $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['These credentials do not match our records.'],
            ]);
        }

        $token = $user->createToken(
            $data['device_name'],
            ['bookmarks:read', 'bookmarks:write'],
        );

        return response()->json(['token' => $token->plainTextToken], 201);
    }

    public function destroy(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json(null, 204);
    }
}

createToken() returns the plain-text token exactly once. Sanctum stores only a SHA-256 hash of it, so a database leak does not leak working tokens. The abilities (bookmarks:read, bookmarks:write) are plain strings you invent; you could also hand out read-only tokens to a reporting script. Both failure cases (unknown email, wrong password) give the same message, so the endpoint does not reveal which emails are registered.

Step 4: validation, resource and controller

Create the pieces with Artisan:

Terminal
php artisan make:request StoreBookmarkRequest
php artisan make:resource BookmarkResource
php artisan make:controller Api/V1/BookmarkController --api
PHP
class StoreBookmarkRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->tokenCan('bookmarks:write');
    }

    /** @return array<string, array<int, string>> */
    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:120'],
            'url' => ['required', 'url:http,https', 'max:2048'],
        ];
    }
}

A failed authorize() produces a 403, a failed rules() check a 422 with an errors object. The url:http,https rule rejects javascript: and ftp: addresses, so you never store a link that is dangerous to render later.

PHP
class BookmarkResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'url' => $this->url,
            'created_at' => $this->created_at->toIso8601String(),
        ];
    }
}

The resource is the public contract. It lists fields one by one, so adding a column to the table never leaks into the API by accident. Now the controller:

PHP
class BookmarkController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        abort_unless($request->user()->tokenCan('bookmarks:read'), 403);

        return BookmarkResource::collection(
            $request->user()->bookmarks()->orderByDesc('id')->paginate(15)
        );
    }

    public function store(StoreBookmarkRequest $request): JsonResponse
    {
        $bookmark = $request->user()->bookmarks()->create($request->validated());

        return (new BookmarkResource($bookmark))
            ->response()
            ->setStatusCode(201);
    }

    public function show(Request $request, int $bookmark): BookmarkResource
    {
        abort_unless($request->user()->tokenCan('bookmarks:read'), 403);

        return new BookmarkResource(
            $request->user()->bookmarks()->findOrFail($bookmark)
        );
    }
}

This needs a bookmarks() relationship (hasMany) on User. Notice that show looks the bookmark up through $request->user()->bookmarks(). A bookmark owned by someone else is simply "not found" (404), which is better than 403, because it does not confirm that the ID exists. A paginated resource collection automatically adds links and meta (current page, total) next to data.

Finally, make sure errors come back as JSON even if a client forgets the Accept: application/json header, in bootstrap/app.php:

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

The API in plain PHP

The next example is a stand-in for the finished API: one Api class that checks a bearer token (stored hashed, like Sanctum), enforces abilities, validates input, returns 404 for other people's records and shapes output like a resource. It is not Laravel, but each line corresponds to a step above.

PHP Simulating the bookmarks API

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.

Read the output from top to bottom. No token gives 401. Bob's read-only token gets 403 on a write. Ada's invalid body gives 422 with one message per field. A valid request gives 201, and only the listed resource fields come back, no owner. Bob asking for Ada's bookmark gets 404, and an unknown version gets 404 too.

Step 5: rate limiting

The throttle:api middleware needs a limiter named api. Depending on how the app was scaffolded, a default may not exist, so define your own in AppServiceProvider::boot() to be sure (a limiter registered with the same name replaces the default):

PHP
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

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

Signed-in users are counted per user, so one office behind a single IP address does not share a quota; anonymous traffic is counted per IP. When the limit is exceeded Laravel answers 429 Too Many Requests and sets X-RateLimit-Remaining and Retry-After headers, so well-behaved clients know when to come back. The counters live in your cache, so use a shared store such as Redis in production when you run more than one server.

The idea behind a fixed-window limiter is small enough to build, with a fake clock so the output never changes:

PHP A fixed-window rate limiter

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 fourth request from user:1 is refused with a Retry-After of 49 seconds, user:2 has its own counter, and at second 61 a new window opens. Laravel's real limiter does the same bookkeeping in the cache with atomic operations, so two simultaneous requests cannot both slip through.

Step 6: feature tests

An API is easy to test, because requests and JSON are all there is. With Pest and Sanctum's test helper:

PHP
use App\Models\Bookmark;
use App\Models\User;
use Laravel\Sanctum\Sanctum;

use function Pest\Laravel\getJson;
use function Pest\Laravel\postJson;

uses(Illuminate\Foundation\Testing\RefreshDatabase::class);

it('rejects requests without a token', function () {
    getJson('/api/v1/bookmarks')->assertUnauthorized();
});

it('creates a bookmark for the token owner', function () {
    $user = User::factory()->create();
    Sanctum::actingAs($user, ['bookmarks:write']);

    postJson('/api/v1/bookmarks', ['title' => 'PHP', 'url' => 'https://php.net'])
        ->assertCreated()
        ->assertJsonPath('data.title', 'PHP')
        ->assertJsonMissingPath('data.user_id');

    expect($user->bookmarks()->count())->toBe(1);
});

it('validates the url scheme', function () {
    Sanctum::actingAs(User::factory()->create(), ['bookmarks:write']);

    postJson('/api/v1/bookmarks', ['title' => 'x', 'url' => 'javascript:alert(1)'])
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['url']);
});

it('hides bookmarks of other users', function () {
    $bookmark = Bookmark::factory()->create();
    Sanctum::actingAs(User::factory()->create(), ['bookmarks:read']);

    getJson("/api/v1/bookmarks/{$bookmark->id}")->assertNotFound();
});

Each test checks one rule from the table at the top: authentication, ownership, validation and the shape of the response. Run them with php artisan test --compact.

Where to go from here

  • Add PUT and DELETE for bookmarks, with a policy instead of the ownership query.
  • Add filtering (?tag=php) and cursor pagination from API design.
  • Generate documentation from your routes (an OpenAPI file) and publish it for client developers.
  • Set a token expiry in config/sanctum.php and prune old tokens with the scheduler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is user_id left out of the Bookmark model's $fillable list?

    Only fields in $fillable can be set from request data. The owner is set through $request->user()->bookmarks()->create(), so it always reflects the token, never the request body.
  2. 2. A client asks for a bookmark that exists but belongs to another user. Which response is best?

    Looking the record up through the signed-in user's own relationship makes foreign records invisible. A 404 does not confirm that the ID exists.
  3. 3. What does Sanctum store in the personal_access_tokens table for a token?

    createToken() returns the plain-text value once. Only its hash is stored, so a leaked table cannot be used to call the API.
  4. 4. What is the main purpose of a BookmarkResource class?

    A resource lists the output fields explicitly. It is the public contract of the endpoint and keeps internal columns private.
  5. 5. Why does the token endpoint get its own, stricter rate limit?

    Login endpoints invite brute-force attacks, so they get a tight limit (here 5 per minute per IP) while ordinary endpoints get a generous one.

Summary

  • php artisan install:api adds Sanctum and routes/api.php; add HasApiTokens to the user model.
  • Put the API under a version prefix and namespace (/api/v1, Api\V1) so you can evolve it later.
  • Issue tokens with createToken() and abilities; Sanctum stores only a hash. Check abilities with tokenCan().
  • Validate in form requests, shape output with API resources, and look records up through the owner's relationship.
  • Define a named rate limiter and apply a stricter one to login.
  • Test status codes, JSON paths, validation errors and ownership with Sanctum::actingAs().

Next: Project: A Task Manager with Livewire