Lesson 34 of 50 - Learn how to create REST APIs, return JSON responses, handle HTTP methods, and test API endpoints in Laravel.
API stands for Application Programming Interface. An API allows different applications to communicate with each other.
For example, a mobile application can request student information from a Laravel backend API.
Example API response:
{
"id": 1,
"name": "Rahul Kumar",
"email": "rahul@example.com",
"course": "ADCA"
}
Common API uses include:
APIs commonly exchange data using JSON, although other formats are also possible.
If you do not already have a Laravel project, create one using Composer.
composer create-project laravel/laravel student-api
cd student-api
php artisan serve
Check your Laravel version:
php artisan --version
In current Laravel releases, API routing can be installed or enabled using:
php artisan install:api
This command is available in supported Laravel
versions and configures API routing, including
routes/api.php, and API authentication
scaffolding for Sanctum.
If your project already has API routes configured, inspect the existing files before running installation commands again. Older Laravel versions may use a different setup process.
Open routes/api.php and add a simple
GET route.
<?php
use Illuminate\Support\Facades\Route;
Route::get('/hello', function () {
return response()->json([
'message' => 'Hello from Laravel API!',
]);
});
Start the development server:
php artisan serve
Open this URL in your browser or API testing tool:
http://127.0.0.1:8000/api/hello
Expected JSON response:
{
"message": "Hello from Laravel API!"
}
In the standard Laravel API route configuration,
routes in routes/api.php automatically
receive the /api URL prefix.
APIs commonly return JSON instead of HTML pages. Laravel can convert arrays and objects into JSON responses automatically.
Return a message:
Route::get('/message', function () {
return response()->json([
'success' => true,
'message' => 'API is working',
]);
});
Return a list of students:
Route::get('/students', function () {
return response()->json([
[
'id' => 1,
'name' => 'Rahul',
'course' => 'ADCA',
],
[
'id' => 2,
'name' => 'Priya',
'course' => 'Tally Prime',
],
]);
});
Return a custom HTTP status code:
Route::get('/student-not-found', function () {
return response()->json([
'message' => 'Student not found',
], 404);
});
Common status codes include:
| Status Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthenticated |
| 403 | Forbidden |
| 404 | Not Found |
| 422 | Validation Error |
| 500 | Internal Server Error |
REST APIs commonly use different HTTP methods depending on the operation being performed.
| Method | Purpose |
|---|---|
| GET | Retrieve records. |
| POST | Create a record. |
| PUT | Replace or update a resource. |
| PATCH | Partially update a resource. |
| DELETE | Delete a resource. |
Example API routes:
use Illuminate\Support\Facades\Route;
Route::get('/students', function () {
return response()->json([
'message' => 'Get all students',
]);
});
Route::post('/students', function () {
return response()->json([
'message' => 'Create a student',
], 201);
});
Route::put('/students/{id}', function ($id) {
return response()->json([
'message' => 'Replace student',
'id' => $id,
]);
});
Route::patch('/students/{id}', function ($id) {
return response()->json([
'message' => 'Update student fields',
'id' => $id,
]);
});
Route::delete('/students/{id}', function ($id) {
return response()->json([
'message' => 'Delete student',
'id' => $id,
]);
});
These examples demonstrate routing only. The POST, PUT, PATCH, and DELETE routes do not yet change database records.
Laravel's Request object provides access to data sent by a frontend or API client.
Example POST API route:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/students', function (Request $request) {
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255'],
'course' => ['required', 'string', 'max:100'],
]);
return response()->json([
'message' => 'Student data validated successfully',
'student' => $validated,
], 201);
});
Send a JSON request body like this using Postman or another API client:
{
"name": "Rahul Kumar",
"email": "rahul@example.com",
"course": "ADCA"
}
Request headers:
Content-Type: application/json
Accept: application/json
The Accept: application/json header
asks Laravel to return validation errors in JSON
format for typical API requests.
This example validates data but does not save it. Database persistence will be covered in CRUD and API resource lessons.
Controllers keep route definitions clean and organize application logic into reusable methods.
Create a controller:
php artisan make:controller Api/StudentController
Open
app/Http/Controllers/Api/StudentController.php.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class StudentController extends Controller
{
public function index()
{
return response()->json([
'message' => 'Student list',
'data' => [],
]);
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'email', 'max:255'],
]);
return response()->json([
'message' => 'Student data received',
'data' => $validated,
], 201);
}
public function show(string $id)
{
return response()->json([
'message' => 'Student details',
'id' => $id,
]);
}
}
Register controller routes:
use App\Http\Controllers\Api\StudentController;
use Illuminate\Support\Facades\Route;
Route::get('/students', [StudentController::class, 'index']);
Route::post('/students', [StudentController::class, 'store']);
Route::get('/students/{id}', [StudentController::class, 'show']);
The controller examples return sample responses. Connect a model and database queries when you are ready to build a functional student API.
You can test Laravel API endpoints using Postman, Insomnia, an HTTP client, or command-line tools such as curl.
Test a GET request using curl:
curl -H "Accept: application/json" \
http://127.0.0.1:8000/api/students
Test a POST request using curl:
curl -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{"name":"Rahul Kumar","email":"rahul@example.com"}' \
http://127.0.0.1:8000/api/students
Check registered routes:
php artisan route:list --path=api
Common troubleshooting steps:
Do not expose exception details or sensitive debug information to public API clients in production.
Build a basic student API using Laravel.
Challenge:
Build a student API with database-backed CRUD operations. Return student records as JSON, validate all incoming data, and protect private endpoints with authentication and authorization.
Never assume that an API is secure simply because it returns JSON. Validate input, authenticate protected requests, authorize access to records, and use HTTPS in production.
1. Which format is commonly used for API responses?
2. Which HTTP method is commonly used to create a resource?
3. Which Laravel object provides access to incoming request data?