Featured image of post Build a REST API with Laravel: A Quick Guide

Build a REST API with Laravel: A Quick Guide

Learn how to build a REST API with Laravel in this comprehensive guide. From prerequisites to best practices, get step-by-step instructions and code examples.

A REST (Representational State Transfer) API is an architectural style for designing networked applications, allowing them to communicate via HTTP requests in a stateless manner. Laravel, a popular PHP framework, is an excellent choice for building REST APIs due to its robust features and elegant syntax.

Prerequisites

Before you start, ensure you have:

  • Basic Knowledge of PHP
  • Familiarity with Laravel
  • Composer Installed
  • A Local Development Environment (e.g., XAMPP, WAMP, or Laravel Homestead)

Step-by-Step Instructions

Step 1: Setting Up the Laravel Project

Create a new Laravel project using Composer:

1
composer create-project --prefer-dist laravel/laravel rest-api

Navigate to the project directory:

1
cd rest-api

Step 2: Configuring the Environment Set up your environment configuration in the .env file. Update your database credentials:

1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=rest_api
DB_USERNAME=root
DB_PASSWORD=password

Step 3: Creating the Database Create the database using your preferred database management tool (e.g., phpMyAdmin, MySQL Workbench) with the name specified in the .env file.

Step 4: Defining Routes Open routes/api.php and define the routes for your API:

1
2
3
4
5
6
7
8
9
use App\Http\Controllers\API\UserController;

Route::middleware('api')->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::get('/users/{id}', [UserController::class, 'show']);
    Route::post('/users', [UserController::class, 'store']);
    Route::put('/users/{id}', [UserController::class, 'update']);
    Route::delete('/users/{id}', [UserController::class, 'destroy']);
});

Step 5: Creating Controllers Generate a controller to handle the API requests:

1
php artisan make:controller API/UserController

Open app/Http/Controllers/API/UserController.php and implement the methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
namespace App\Http\Controllers\API;

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

class UserController extends Controller
{
    public function index()
    {
        return User::all();
    }

    public function show($id)
    {
        return User::find($id);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
        ]);

        $user = User::create($validated);
        return response()->json($user, 201);
    }

    public function update(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $user->update($request->all());
        return response()->json($user, 200);
    }

    public function destroy($id)
    {
        User::destroy($id);
        return response()->json(null, 204);
    }
}

Step 6: Creating Models and Migrations

Generate a model and migration for the User:

1
php artisan make:model User -m

Open the migration file in database/migrations/ and define the table structure:

1
2
3
4
5
6
7
8
9
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamps();
    });
}

Run the migration to create the table:

1
php artisan migrate

Step 7: Running the Server

Start the development server using the following command:

1
php artisan serve

The server will start at http://localhost:8000, where you can access your Laravel application.

Demo

To test your REST API, you can use a tool like Postman or curl to send HTTP requests to your Laravel application. Here are some example requests:

Fetch All Users

1
curl -X GET http://localhost:8000/api/users

Fetch a Single User

1
curl -X GET http://localhost:8000/api/users/{id}

Replace {id} with the ID of the user you want to fetch.

Create a New User

1
2
3
curl -X POST http://localhost:8000/api/users -H
"Content-Type: application/json" -d
'{"name": "John Doe", "email": "john@example.com"}'

Update a User

1
2
3
curl -X PUT http://localhost:8000/api/users/{id} -H
"Content-Type: application/json" -d
'{"name": "Jane Doe", "email": "jane@example.com"}'

Replace {id} with the ID of the user you want to update.

Delete a User

1
curl -X DELETE http://localhost:8000/api/users/{id}

Replace {id} with the ID of the user you want to delete.

Additional Resources

For further learning, check out:

By following this guide, you’ll have a solid foundation to build a REST API with Laravel, whether for small projects or large-scale applications.