Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Blog · Laravel

Building a REST API with Laravel: A Complete Guide

Building a REST API with Laravel: A Complete Guide

A REST API in Laravel is really just routes that return JSON instead of HTML, plus a bit of discipline around status codes and validation. Here's how to build one that won't fall apart the moment a frontend team starts using it.

Setting Up API Routes

API routes live in routes/api.php and are automatically prefixed with /api. Laravel also disables session state on this group by default, which is exactly what you want for a stateless API.

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

That single line generates index, store, show, update, and destroy routes — the full CRUD set — pointing at PostController.

Returning Proper JSON Responses

Eloquent models already serialize to JSON automatically, but wrap them in an API Resource so you control exactly what shape goes out over the wire — and never accidentally leak a column you didn't mean to expose:

php artisan make:resource PostResource
class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'excerpt' => Str::limit($this->body, 120),
            'published_at' => $this->published_at?->toDateString(),
        ];
    }
}

Validating Incoming Requests

Never trust the request body. Move validation into a dedicated Form Request class rather than inline in the controller — it keeps the controller readable and the rules reusable:

class StorePostRequest extends FormRequest
{
    public function rules()
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string'],
        ];
    }
}

Status Codes That Actually Mean Something

  • 200 — successful GET/PUT
  • 201 — resource created (POST)
  • 204 — success, no content to return (DELETE)
  • 422 — validation failed (Laravel returns this automatically from Form Requests)
  • 404 — resource not found

Consistent status codes are what separate an API that's pleasant to consume from one that makes every client guess.

Authentication with Sanctum

For a first-party SPA or mobile app, Laravel Sanctum gives you token-based auth without the overhead of a full OAuth server. Once installed, protect routes with a single middleware:

Route::middleware('auth:sanctum')->apiResource('posts', PostController::class);

That's genuinely most of what a production API needs on day one — resources, validation, correct status codes, and token auth. Everything else (rate limiting, versioning, pagination) layers on top of this foundation.

Laravel for Beginners: Setting Up Your First Project

Laravel for Beginners: Setting Up Your First Project

A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.

Laravel Eloquent Relationships Explained with Real Examples

Laravel Eloquent Relationships Explained with Real Examples

One-to-many, many-to-many, polymorphic, and the N+1 query trap that catches almost every Laravel developer at least once.

Queues and Jobs in Laravel: Processing Tasks in the Background

Queues and Jobs in Laravel: Processing Tasks in the Background

Why anything that talks to the outside world belongs in a queued job, and how to dispatch, delay, and chain them correctly.

Esc