Building RESTful APIs with Laravel: A Complete Guide

Introduction

In today’s web development world, RESTful APIs play a major role in connecting frontend applications, mobile apps, and third-party services with backend systems. APIs allow different applications to communicate with each other efficiently.

Among PHP frameworks, Laravel is one of the most popular choices for building REST APIs. Its powerful Eloquent ORM, routing system, and built-in tools like Sanctum and Passport make it easier to develop secure and scalable APIs.

In this guide, we’ll walk through the process of creating a RESTful API in Laravel step by step. By the end, you’ll have a fully functional API that can handle CRUD (Create, Read, Update, Delete) operations and authentication.


Step 1: Setting Up a Laravel Project

First, make sure you have Composer installed. Then create a new Laravel project:

composer create-project laravel/laravel laravel-api cd laravel-api php artisan serve

Your project will be available at:
👉 http://127.0.0.1:8000


Step 2: Configure Database

Open the .env file and configure your database:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_api DB_USERNAME=root DB_PASSWORD=

Then create the database in MySQL:

CREATE DATABASE laravel_api;

Step 3: Create Migration and Model

Let’s create a Post model for our blog API:

php artisan make:model Post -m

This will create:

  • Model: app/Models/Post.php
  • Migration: database/migrations/xxxx_xx_xx_create_posts_table.php

Update the migration file:

public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->timestamps(); }); }

Run migration:

php artisan migrate

Step 4: Create Controller

Generate a controller for handling API requests:

php artisan make:controller Api/PostController --api

This creates PostController with REST methods.


Step 5: Define API Routes

Open routes/api.php and add:

use App\Http\Controllers\Api\PostController; Route::apiResource('posts', PostController::class);

This automatically creates routes:

  • GET /api/posts → List all posts
  • POST /api/posts → Create a new post
  • GET /api/posts/{id} → Show a single post
  • PUT /api/posts/{id} → Update a post
  • DELETE /api/posts/{id} → Delete a post


Step 6: Implement Controller Logic

In app/Http/Controllers/Api/PostController.php:

namespace App\Http\Controllers\Api; use App\Models\Post; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PostController extends Controller { // Get all posts public function index() { return Post::all(); } // Store new post public function store(Request $request) { $request->validate([ 'title' => 'required|max:255', 'content' => 'required', ]); return Post::create($request->all()); } // Show single post public function show($id) { return Post::findOrFail($id); } // Update post public function update(Request $request, $id) { $post = Post::findOrFail($id); $post->update($request->all()); return $post; } // Delete post public function destroy($id) { Post::destroy($id); return response()->json(['message' => 'Post deleted successfully']); } }

Also, update Post.php model:

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

Step 7: Format Responses with API Resources

Laravel provides API Resources for clean JSON responses.

Create resource:

php artisan make:resource PostResource

In app/Http/Resources/PostResource.php:

public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'content' => $this->content, 'created_at' => $this->created_at->toDateTimeString(), ]; }

Use it in PostController:

use App\Http\Resources\PostResource; public function index() { return PostResource::collection(Post::all()); } public function show($id) { return new PostResource(Post::findOrFail($id)); }

Step 8: Authentication with Laravel Sanctum

Install Sanctum for token-based authentication:

composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate

Add HasApiTokens to User model:

use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; }

Update config/auth.php:

'guards' => [ 'api' => [ 'driver' => 'sanctum', 'provider' => 'users', ], ],

Create auth routes in api.php:

use App\Http\Controllers\Api\AuthController; Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->group(function () { Route::apiResource('posts', PostController::class); });

Step 9: Error Handling & Validation

Laravel automatically handles validation errors with JSON response:

{ "message": "The given data was invalid.", "errors": { "title": ["The title field is required."] } }

For custom errors, use:

return response()->json(['error' => 'Not Found'], 404);

Step 10: Test with Postman

  • POST /api/register → Create user
  • POST /api/login → Get token
  • Use token in Authorization → Bearer Token
  • Test CRUD endpoints for posts

Post a Comment

Previous Post Next Post

Contact Form