GICT knowledge base
How to build Your Own Restful APIs in Laravel
Published
This guide includes a step-by-step explanation of how to create, read, update, and delete (CRUD) data through a simple API. By the end, you’ll understand the core concepts behind RESTful APIs and how Laravel makes it easy to build one.
APIs (Application Programming Interfaces) are how different software applications communicate with each other. Whether it’s a mobile app retrieving user data from a server or a website fetching data from an external source, APIs are critical to modern web development.
Laravel, one of the most popular PHP frameworks, comes with powerful tools for building APIs. In this guide, we’ll walk you through creating a RESTful API using Laravel and handling basic CRUD operations on user data.
This blog will cover:
- What a RESTful API is.
- How to set up routes, controllers, and models in Laravel.
- Handling API requests for creating, reading, updating, and deleting users.
- Testing your API with tools like Postman.
- Validating input data and handling errors.
What is a RESTful API?
Let’s break this down for absolute beginners:
- REST (Representational State Transfer): This is an architectural style for designing networked applications. It uses standard HTTP methods (GET, POST, PUT, DELETE) to perform actions on resources (like user data).
- API (Application Programming Interface): This allows different software systems to communicate. In our case, we’ll use a RESTful API to let other applications (like mobile apps) communicate with our Laravel backend.
For example:
- GET request to /users will retrieve all users.
- POST request to /users will create a new user.
- PUT request to /users/{id} will update an existing user.
- DELETE request to /users/{id} will delete a user.
Each HTTP request corresponds to a specific action in the API, and this guide will show you how to set it up.
Prerequisites
Before we start coding, make sure you have the following in place:
- Laravel installed: Install Laravel globally or within your project directory using this command:
composer create-project laravel/laravel rest-api - Basic PHP and Laravel knowledge: You don’t need to be an expert, but understanding the basics of PHP and Laravel will help.
- A database set up: Make sure you’ve configured a MySQL or SQLite database in your Laravel
.envfile.
Once you have Laravel installed and a database ready, you’re good to go!
Step 1: Setting Up API Routes
The first step in building any API is defining routes. These routes map HTTP requests to specific controller actions. In Laravel, you define API routes in the routes/api.php file. This file is specifically meant for API routes and automatically uses the /api prefix in the URL.
Let’s start by defining some basic routes for user CRUD operations:
// routes/api.php
use App\Http\Controllers\UserController;
// Fetch all users
Route::get('/users', [UserController::class, 'index']);
// Fetch a specific user by ID
Route::get('/users/{id}', [UserController::class, 'show']);
// Create a new user
Route::post('/users', [UserController::class, 'store']);
// Update an existing user
Route::put('/users/{id}', [UserController::class, 'update']);
// Delete a user
Route::delete('/users/{id}', [UserController::class, 'destroy']);
Each of these routes maps to a specific function in the UserController. For example, a GET request to /users will invoke the index method to retrieve all users, while a POST request to /users will invoke the store method to create a new user.
Step 2: Creating the Controller
Next, we need to create a controller to handle the logic for each route. Controllers in Laravel act as the “brains” behind the API—they handle requests, interact with the database, and return responses.
Run the following command to create a UserController:
php artisan make:controller UserController
This creates a file called UserController.php in the app/Http/Controllers/ directory. Now, let’s define the functions inside this controller to handle user data:
// app/Http/Controllers/UserController.php
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
// Fetch all users
public function index() {
return response()->json(User::all(), 200); // 200 means OK
}
// Fetch a specific user by ID
public function show($id) {
$user = User::find($id);
if ($user) {
return response()->json($user, 200); // Return the user data
} else {
return response()->json(['message' => 'User not found'], 404); // Return error
}
}
// Create a new user
public function store(Request $request) {
$user = User::create($request->all()); // Create the user
return response()->json($user, 201); // 201 means resource created
}
// Update an existing user
public function update(Request $request, $id) {
$user = User::find($id);
if ($user) {
$user->update($request->all());
return response()->json($user, 200);
} else {
return response()->json(['message' => 'User not found'], 404);
}
}
// Delete a user
public function destroy($id) {
$user = User::find($id);
if ($user) {
$user->delete();
return response()->json(['message' => 'User deleted'], 200);
} else {
return response()->json(['message' => 'User not found'], 404);
}
}
}
Here’s a breakdown of what each function does:
- index: Returns a list of all users.
- show: Returns a specific user based on the ID.
- store: Creates a new user with the data from the request.
- update: Updates an existing user based on the ID.
- destroy: Deletes a user by their ID.
The response is always sent back as JSON, which is the standard format for APIs.
Step 3: Creating the Model
In Laravel, models represent the data in your application. Each model corresponds to a table in the database. We need to create a User model that will allow us to interact with the users table.
Run this command to generate the model:
php artisan make:model User
Next, open the generated User.php file in app/Models/ and define the fields that should be mass-assignable. Mass assignment means allowing users to create or update multiple fields at once:
// app/Models/User.php
class User extends Model
{
protected $fillable = ['name', 'email', 'password'];
}
By defining fillable fields, we allow the name, email, and password fields to be filled through user input.
Step 4: Creating the Database Table
We need a table to store the user data. In Laravel, you can use migrations to create tables in the database. Let’s create a migration for the users table.
Run this command:
php artisan make:migration create_users_table
The generated migration file is found in the database/migrations/ folder. Open the file and define the table’s structure:
// database/migrations/xxxx_xx_xx_create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps(); // created_at and updated_at fields
});
Run the migration to create the table in the database:
php artisan migrate
This will create the users table with the name, email, and password fields, as well as created_at and updated_at timestamps.
Step 5: Testing the API
With our routes, controller, and model in place, our API is ready to be tested. You can test the API using tools like Postman, or you can use cURL commands in your terminal.
Here are a few examples of how to test the API:
- GET Request to Fetch All Users:
curl -X GET http://localhost:8000/api/usersThis will return a JSON response with a list of all users.
- POST Request to Create a New User:
curl -X POST http://localhost:8000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "John Doe", "email": "[email protected]", "password": "secret"}'This will create a new user and return the created user data.
- PUT Request to Update an Existing User:
curl -X PUT http://localhost:8000/api/users/1 \ -H "Content-Type: application/json" \ -d '{"name": "Jane Doe"}'This will update the name of the user with ID 1.
- DELETE Request to Remove a User:
curl -X DELETE http://localhost:8000/api/users/1This will delete the user with ID 1.
Step 6: Input Validation
When building APIs, it’s essential to validate user input to ensure only valid data is processed. Laravel makes validation simple. Let’s update the store method in the UserController to validate the incoming request data.
public function store(Request $request) {
// Validate input
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6',
]);
// Create user if validation passes
$user = User::create($request->all());
return response()->json($user, 201);
}
This ensures that only valid data is passed when creating a new user. If the validation fails, Laravel automatically returns a JSON response with the appropriate error messages.
Conclusion
Creating a RESTful API in Laravel is straightforward, thanks to the framework’s powerful routing, controllers, and models. In this guide, we covered the basics of setting up an API, handling CRUD operations, and validating input. You now have a functional API that can create, read, update, and delete user data.
The benefits of building RESTful APIs in Laravel include:
- Simplicity: Laravel’s routing and controllers make it easy to set up.
- Flexibility: You can add complex features like middleware, authentication, and rate-limiting with ease.
- Scalability: Laravel’s architecture allows you to build both small and large APIs that can grow with your application.
With these skills, you’re ready to explore more advanced topics like API authentication, versioning, and documentation.
Related guides
Handling PATCH and PUT Requests with Next.js and Laravel
Learn to handle PATCH and PUT requests between Next.js and Laravel.
LaravelHow to Get Environment Variables in Laravel React
Learn how to get environment variables in Laravel React apps. Simple guide covering MIX_, VITE_ prefixes and Laravel backend methods with code examples.
LaravelLaravel 12 Global Scope Guide – Easy Query Filtering
Learn how to use Laravel 12’s new global scope features to secure, simplify, and streamline database queries across your entire application.
LaravelLaravel Debugbar: Ultimate Debug Tool for Faster Development
Stop hunting through scattered log files! Learn journalctl to quickly find what went wrong on your Linux server and fix issues faster.
