How to Create a Simple API with Laravel
Tutorials Publié le 11 Sep 2025

How to Create a Simple API with Laravel

Laravel is one of the most popular PHP frameworks for building modern web applications. In this tutorial, we’ll walk through the basics of creating a RESTful API using Laravel.

1. Set Up a New Laravel Project

Make sure you have Composer installed. Run the following command:

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

Now you can access your project at https://127.0.0.1:8000.

2. Create a Model and Migration

For this tutorial, let’s create a Post model:

php artisan make:model Post -m

Open the migration file in database/migrations and add fields:

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

Then run:

php artisan migrate

3. Seed Some Data (Optional)

You can use Laravel seeders to add test data.

php artisan make:seeder PostSeeder

4. Create a Controller for the API

php artisan make:controller Api/PostController --api

Inside 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 Post::all();
    }

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

        return Post::create($request->all());
    }

    public function show(Post $post)
    {
        return $post;
    }

    public function update(Request $request, Post $post)
    {
        $post->update($request->all());
        return $post;
    }

    public function destroy(Post $post)
    {
        $post->delete();
        return response()->noContent();
    }
}

5. Define API Routes

Open routes/api.php and add:

use App\Http\Controllers\Api\PostController;

Route::apiResource('posts', PostController::class);

6. Test the API

Now you can test endpoints using Postman or cURL:

  • GET /api/posts → Get 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

🎯 Conclusion

With just a few steps, you’ve created a fully functional REST API in Laravel. This API can be connected to a frontend (Vue, React, Angular) or even a mobile app (Flutter).