0
0
Laravelframework~30 mins

API routes in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Building API Routes in Laravel
📖 Scenario: You are creating a simple API for a book store. The API will allow users to get a list of books and add new books.
🎯 Goal: Build API routes in Laravel to handle requests for listing all books and adding a new book.
📋 What You'll Learn
Create a route group with prefix api
Define a GET route /books that returns all books
Define a POST route /books that adds a new book
Use a controller named BookController with methods index and store
💡 Why This Matters
🌍 Real World
API routes are used to build backend services that mobile apps or frontend apps can call to get or send data.
💼 Career
Knowing how to define API routes in Laravel is essential for backend developers building RESTful services.
Progress0 / 4 steps
1
Create the initial API route group
Create a route group with prefix api in routes/api.php using Route::prefix('api')->group(function () { ... });
Laravel
Need a hint?

Use Route::prefix('api')->group(function () { ... }); to start the API routes.

2
Add a GET route for listing books
Inside the api route group, add a GET route /books that uses BookController@index.
Laravel
Need a hint?

Use Route::get('/books', [BookController::class, 'index']); inside the group.

3
Add a POST route for adding a new book
Inside the api route group, add a POST route /books that uses BookController@store.
Laravel
Need a hint?

Use Route::post('/books', [BookController::class, 'store']); inside the group.

4
Complete the API routes with middleware
Add the auth:sanctum middleware to the api route group to protect the routes.
Laravel
Need a hint?

Add ->middleware('auth:sanctum') after prefix('api') to protect the routes.