Building APIs in Laravel 11

Building APIs in Laravel 11 involves setting up routes, controllers, and models to handle API requests and responses. Laravel provides many tools and features to facilitate API development, including route management, middleware, and resource controllers. Here's a comprehensive guide to building APIs in Laravel 11:

Step-by-Step Guide

1. Set Up a New Laravel Project

If you haven't set up your Laravel project, create a new one:


composer create-project laravel/laravel laravel-api cd laravel-api

2. Configure Your Database

Set up your database connection in the .env file:


DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database DB_USERNAME=your_username DB_PASSWORD=your_password

Run the migrations to create the default tables:


php artisan migrate

3. Create a Model and Migration

For demonstration, let's create a simple model and migration for a Post resource:


php artisan make:model Post -m

Edit the generated migration file to define the posts table schema:


// database/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('body'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('posts'); } }

Run the migration:

php artisan migrate

4. Create a Resource Controller

Create a resource controller to handle CRUD operations:

php artisan make:controller Api/PostController --api

5. Define API Routes

Add the routes for your API in the routes/api.php file:

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

6. Implement the Controller Methods

Edit the PostController to implement the CRUD operations:

// app/Http/Controllers/Api/PostController.php
namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\Post; use Illuminate\Http\Request; class PostController extends Controller { public function index() { return response()->json(Post::all()); } public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|string|max:255', 'body' => 'required|string', ]); $post = Post::create($validated); return response()->json($post, 201); } public function show(Post $post) { return response()->json($post); } public function update(Request $request, Post $post) { $validated = $request->validate([ 'title' => 'sometimes|required|string|max:255', 'body' => 'sometimes|required|string', ]); $post->update($validated); return response()->json($post); } public function destroy(Post $post) { $post->delete(); return response()->json(null, 204); } }

7. Add Fillable Properties to the Model

Make sure the Post model has the fillable properties defined:

// app/Models/Post.php
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; protected $fillable = ['title', 'body']; }

8. Add API Authentication (Optional)

If your API requires authentication, you can use Laravel Sanctum for token-based authentication.

Install Sanctum:


composer require laravel/sanctum

Publish the Sanctum configuration:


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

Add Sanctum's middleware to your api middleware group within your app/Http/Kernel.php file:


// app/Http/Kernel.php use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful; protected $middlewareGroups = [ 'web' => [ // other middleware ], 'api' => [ EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];

Add the HasApiTokens trait to your User model:


// app/Models/User.php use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; }

Configure API authentication routes and middleware in your routes/api.php:


use Illuminate\Support\Facades\Route; use App\Http\Controllers\Api\PostController; Route::middleware('auth:sanctum')->group(function () { Route::apiResource('posts', PostController::class); });

9. Testing the API

Use tools like Postman or cURL to test your API endpoints. Here are some examples:

  • Get All Posts:


    GET /api/posts
  • Create a New Post:


    POST /api/posts { "title": "Sample Post", "body": "This is a sample post." }
  • Get a Single Post:


    GET /api/posts/{id}
  • Update a Post:


    PUT /api/posts/{id} { "title": "Updated Post", "body": "This is an updated post." }
  • Delete a Post:


    DELETE /api/posts/{id}

Conclusion

By following these steps, you can build a robust API in Laravel 11. This guide covered setting up routes, controllers, models, and optional API authentication using Laravel Sanctum. Laravel’s powerful features and elegant syntax make API development straightforward and efficient.

Post a Comment

0 Comments