• Fri, Mar 2026

Building REST APIs in Laravel: Step-by-Step Guide for Beginners

Building REST APIs in Laravel: Step-by-Step Guide for Beginners

This complete tutorial walks you through building REST APIs in Laravel. Learn how to structure routes, create controllers, use models, and handle authentication while returning clean JSON responses. Perfect for beginners starting their Laravel API journey.

Introduction

In today’s digital world, REST APIs are the backbone of modern applications. From mobile apps to frontend JavaScript frameworks like React or Vue, APIs allow different systems to communicate seamlessly. Laravel, one of the most popular PHP frameworks, provides an elegant way to build REST APIs with minimal effort.

This guide is designed for beginners who want to understand how to build APIs in Laravel. By the end of this tutorial, you’ll be able to build a fully functional REST API capable of handling requests, returning JSON responses, and even handling authentication.

What is a REST API?

REST (Representational State Transfer) is an architectural style that uses HTTP methods to perform actions on resources. In REST:

  • GET → Retrieve data
  • POST → Create new data
  • PUT/PATCH → Update existing data
  • DELETE → Remove data

Setting Up a Laravel Project

First, let’s create a fresh Laravel project:

composer create-project laravel/laravel laravel-api-demo

Start the development server:

php artisan serve

Laravel comes with API support out of the box. All API routes go into the routes/api.php file.

Understanding API Routes in Laravel

Open routes/api.php. By default, Laravel uses the /api prefix for API routes.


// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/hello', function () {
    return response()->json(['message' => 'Hello from Laravel API!']);
});
    

Now visit http://127.0.0.1:8000/api/hello. You’ll see:


{
  "message": "Hello from Laravel API!"
}
    

Building a CRUD API with Laravel

Let’s build a simple API for managing Books. The API will allow clients to:

  • Create a new book
  • Retrieve all books
  • Retrieve a single book
  • Update a book
  • Delete a book

Step 1: Create Migration and Model

php artisan make:model Book -m

This command creates a model Book and a migration file.


// database/migrations/xxxx_xx_xx_create_books_table.php
public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('author');
        $table->integer('year_published');
        $table->timestamps();
    });
}
    

Run the migration:

php artisan migrate

Step 2: Create Controller

php artisan make:controller Api/BookController --api

This creates a controller with methods tailored for API use.


// app/Http/Controllers/Api/BookController.php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Book;
use Illuminate\Http\Request;

class BookController extends Controller
{
    public function index()
    {
        return response()->json(Book::all());
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'author' => 'required',
            'year_published' => 'required|integer',
        ]);

        $book = Book::create($request->all());

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

    public function show($id)
    {
        return response()->json(Book::findOrFail($id));
    }

    public function update(Request $request, $id)
    {
        $book = Book::findOrFail($id);
        $book->update($request->all());

        return response()->json($book);
    }

    public function destroy($id)
    {
        Book::destroy($id);

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

Step 3: Define API Routes


// routes/api.php
use App\Http\Controllers\Api\BookController;

Route::apiResource('books', BookController::class);
    

Step 4: Enable Mass Assignment


// app/Models/Book.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'author', 'year_published'];
}
    

Testing the API

You can use tools like Postman, Insomnia, or even curl to test your API.

HTTP MethodEndpointAction
GET/api/booksRetrieve all books
POST/api/booksCreate a new book
GET/api/books/{id}Retrieve single book
PUT/PATCH/api/books/{id}Update a book
DELETE/api/books/{id}Delete a book

Adding Authentication to the API

In real-world applications, you don’t want just anyone to access your API. Laravel provides authentication tools like Sanctum for securing APIs.

Step 1: Install Sanctum

composer require laravel/sanctum

Step 2: Publish and Migrate

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Step 3: Add Middleware


// app/Http/Kernel.php
'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
    

Step 4: Protect Routes


// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('books', BookController::class);
});
    

Best Practices for Building REST APIs in Laravel

  • Use apiResource for clean routes.
  • Always return JSON responses with proper status codes.
  • Validate all incoming requests.
  • Use Laravel Sanctum or Passport for authentication.
  • Document your API with tools like Swagger.
  • Handle errors gracefully with JSON error responses.

Conclusion

Building REST APIs in Laravel is beginner-friendly yet powerful enough for production use. You now know how to create routes, controllers, and models, apply CRUD operations, secure APIs with Sanctum, and test with Postman. With these skills, you can start integrating your APIs into mobile apps, SPAs, or even third-party services.

The more you practice, the more confident you’ll become in designing robust, scalable, and secure APIs with Laravel.

This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy