agyanadda@gmail.com

Laravel REST API

Forms, Security and APIs 1 min read Updated Dec 2, 2026 Topic 13 of 13

A REST API lets mobile apps, React or Vue frontends and other servers use your data as JSON. Laravel makes APIs very easy.

Set up

In Laravel 11 and later, run php artisan install:api. It creates routes/api.php and installs Sanctum for token login. Every route in this file gets the /api prefix.

API resource routes

Route::apiResource('posts', PostController::class); creates five routes — like resource, but without the create and edit form pages:

  • GET /api/posts — list
  • POST /api/posts — create
  • GET /api/posts/{post} — show one
  • PUT /api/posts/{post} — update
  • DELETE /api/posts/{post} — delete

Returning JSON

Return a model or collection and Laravel converts it to JSON. Use response()->json($data, 201) to set a status code. Common codes: 200 OK, 201 Created, 204 No Content, 404 Not Found, 422 validation failed.

Protecting the API

Wrap routes in auth:sanctum and send the token in the Authorization: Bearer <token> header. Test endpoints with Postman or curl.

Example

Example — A JSON API for posts PHP
<?php
// routes/api.php
Route::apiResource('posts', PostController::class)->only(['index', 'show']);
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('posts', PostController::class)->except(['index', 'show']);
});

// app/Http/Controllers/PostController.php
public function index()
{
    return Post::latest()->paginate(10);
}

public function store(Request $request)
{
    $data = $request->validate(['title' => 'required|max:255', 'body' => 'required']);
    $post = $request->user()->posts()->create($data);

    return response()->json($post, 201);
}

public function destroy(Post $post)
{
    $post->delete();

    return response()->noContent();   // 204
}

GET /api/posts returns JSON like {"data":[{"id":1,"title":"Hello Eloquent",...}],"current_page":1,...}. Creating and deleting need a Sanctum token; invalid input returns status 422 with the errors as JSON.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which status code means a new resource was created?

Exercise 2 True / False

Route::apiResource includes the create and edit form routes.

Exercise 3 Fill in the Blank

Routes in routes/api.php get the /___ prefix.

Frequently Asked Questions

Create an API Resource with php artisan make:resource PostResource and return only the fields you want in its toArray() method. Then return new PostResource($post) or PostResource::collection($posts). This also hides columns you add later by accident.