This complete tutorial walks you through building REST APIs in Laravel. Learn how to structure routes, create controllers, use models, and handle authentication while returning clean JSON responses. Perfect for beginners starting their Laravel API journey.
In today’s digital world, REST APIs are the backbone of modern applications. From mobile apps to frontend JavaScript frameworks like React or Vue, APIs allow different systems to communicate seamlessly. Laravel, one of the most popular PHP frameworks, provides an elegant way to build REST APIs with minimal effort.
This guide is designed for beginners who want to understand how to build APIs in Laravel. By the end of this tutorial, you’ll be able to build a fully functional REST API capable of handling requests, returning JSON responses, and even handling authentication.
What is a REST API?
REST (Representational State Transfer) is an architectural style that uses HTTP methods to perform actions on resources. In REST:
Laravel comes with API support out of the box. All API routes go into the routes/api.php file.
Understanding API Routes in Laravel
Open routes/api.php. By default, Laravel uses the /api prefix for API routes.
// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/hello', function () {
return response()->json(['message' => 'Hello from Laravel API!']);
});
Now visit http://127.0.0.1:8000/api/hello. You’ll see:
{
"message": "Hello from Laravel API!"
}
Building a CRUD API with Laravel
Let’s build a simple API for managing Books. The API will allow clients to:
Create a new book
Retrieve all books
Retrieve a single book
Update a book
Delete a book
Step 1: Create Migration and Model
php artisan make:model Book -m
This command creates a model Book and a migration file.
// database/migrations/xxxx_xx_xx_create_books_table.php
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('author');
$table->integer('year_published');
$table->timestamps();
});
}
This creates a controller with methods tailored for API use.
// app/Http/Controllers/Api/BookController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Book;
use Illuminate\Http\Request;
class BookController extends Controller
{
public function index()
{
return response()->json(Book::all());
}
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'author' => 'required',
'year_published' => 'required|integer',
]);
$book = Book::create($request->all());
return response()->json($book, 201);
}
public function show($id)
{
return response()->json(Book::findOrFail($id));
}
public function update(Request $request, $id)
{
$book = Book::findOrFail($id);
$book->update($request->all());
return response()->json($book);
}
public function destroy($id)
{
Book::destroy($id);
return response()->json(null, 204);
}
}
Step 3: Define API Routes
// routes/api.php
use App\Http\Controllers\Api\BookController;
Route::apiResource('books', BookController::class);
Step 4: Enable Mass Assignment
// app/Models/Book.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
use HasFactory;
protected $fillable = ['title', 'author', 'year_published'];
}
Testing the API
You can use tools like Postman, Insomnia, or even curl to test your API.
HTTP Method
Endpoint
Action
GET
/api/books
Retrieve all books
POST
/api/books
Create a new book
GET
/api/books/{id}
Retrieve single book
PUT/PATCH
/api/books/{id}
Update a book
DELETE
/api/books/{id}
Delete a book
Adding Authentication to the API
In real-world applications, you don’t want just anyone to access your API. Laravel provides authentication tools like Sanctum for securing APIs.
Always return JSON responses with proper status codes.
Validate all incoming requests.
Use Laravel Sanctum or Passport for authentication.
Document your API with tools like Swagger.
Handle errors gracefully with JSON error responses.
Conclusion
Building REST APIs in Laravel is beginner-friendly yet powerful enough for production use. You now know how to create routes, controllers, and models, apply CRUD operations, secure APIs with Sanctum, and test with Postman. With these skills, you can start integrating your APIs into mobile apps, SPAs, or even third-party services.
The more you practice, the more confident you’ll become in designing robust, scalable, and secure APIs with Laravel.
This article is a comprehensive tutorial on using the Prohibited Validation Rules in Laravel. You will learn how to apply prohibited, prohibited_if, and prohibited_unless with clear explanations, real-life scenarios, and code examples. This guide is perfect for developers who want to master advanced validation techniques in Laravel applications.
This detailed tutorial explores request validation in Laravel controllers. You’ll learn multiple techniques—basic controller validation, using form request classes, custom rules, conditional validation, error handling, localization, and best practices. With practical examples, code snippets, and structured explanations, this article is designed for beginners to advance learner.
This guide teaches you how to deploy Laravel applications to production servers. From preparing your environment and configuring Nginx or Apache, to database migrations, caching, performance optimization, CI/CD pipelines, and security practices—this article covers everything step by step.It’s suitable for both beginners and advanced developers who want to ship stable, secure & scalable app.
This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy
These cookies are essential for the website to function properly.
These cookies help us understand how visitors interact with the website.
These cookies are used to deliver personalized advertisements.