Lecture Notes Of Day 13 - Laravel API Development
Lecture Notes Of Day 13
Laravel API Development
Objective:
To learn how to build
RESTful APIs in Laravel.
Expected Outcome:
By the end of the
session, students will be able to create APIs for performing CRUD (Create,
Read, Update, Delete) operations in Laravel.
Introduction to Laravel
API Development
Laravel provides robust
features for API development, including tools to create RESTful APIs
efficiently. RESTful APIs are architectural principles for designing networked
applications that use HTTP methods (GET, POST, PUT, DELETE) to perform CRUD
operations.
What is a RESTful API?
RESTful APIs:
- Stand
for Representational State Transfer.
- Allow
communication between the client and server using HTTP protocols.
- Use
standard HTTP methods like:
- GET:
Retrieve data.
- POST:
Add new data.
- PUT/PATCH:
Update existing data.
- DELETE:
Remove data.
Laravel makes building
RESTful APIs simple with its built-in Route::apiResource functionality.
Step-by-Step Guide to
Building RESTful APIs in Laravel
1. Setting Up the Project
Before starting API
development:
1.
Ensure Laravel is installed.
2.
Open the terminal in your Laravel project
directory.
2. Create a Model and
Migration
1.
Run the following command to create a
model for the resource (e.g., Product):
bash
Copy code
php artisan make:model
Product -m
This will create a Product
model and a migration file.
2.
Define the schema for your resource in the
migration file:
php
Copy code
public function up()
{
Schema::create('products', function
(Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
}
3.
Migrate the database:
bash
Copy code
php artisan migrate
3. Create a Controller
Use the --api flag to
generate a controller specifically for API functionality:
bash
Copy code
php artisan
make:controller ProductController --api
The ProductController
will handle all API requests.
4. Define API Routes
Laravel provides the Route::apiResource
method to define RESTful routes for a resource in a single line:
php
Copy code
use Illuminate\Support\Facades\Route;
Route::apiResource('products',
ProductController::class);
This automatically
creates routes for:
- GET
/products - Retrieve all products.
- GET
/products/{id} - Retrieve a single product by ID.
- POST
/products - Create a new product.
- PUT
/products/{id} - Update a product by ID.
- DELETE
/products/{id} - Delete a product by ID.
5. Implement CRUD Methods
in the Controller
Add logic to handle API
requests in ProductController:
- Index
Method (GET /products): Retrieve all
products.
php
Copy code
public function index()
{
return Product::all();
}
- Show
Method (GET /products/{id}): Retrieve a single
product.
php
Copy code
public function show($id)
{
return Product::findOrFail($id);
}
- Store
Method (POST /products): Add a new product.
php
Copy code
public function store(Request
$request)
{
$validated = $request->validate([
'name' => 'required',
'description' => 'required',
'price' => 'required|numeric',
]);
return Product::create($validated);
}
- Update
Method (PUT /products/{id}): Update an existing
product.
php
Copy code
public function update(Request
$request, $id)
{
$product = Product::findOrFail($id);
$validated = $request->validate([
'name' => 'required',
'description' => 'required',
'price' => 'required|numeric',
]);
$product->update($validated);
return $product;
}
- Destroy
Method (DELETE /products/{id}): Delete a product.
php
Copy code
public function destroy($id)
{
$product = Product::findOrFail($id);
$product->delete();
return response()->json(['message' =>
'Product deleted successfully']);
}
6. Test the APIs Using
Postman
Postman is a tool for
testing APIs. Follow these steps:
1.
Open Postman and create a new request.
2.
Set the HTTP method (GET, POST, PUT,
DELETE).
3.
Provide the endpoint URL (e.g., http://127.0.0.1:8000/api/products).
4.
Add any necessary headers (e.g., Content-Type:
application/json).
5.
For POST/PUT requests, add a JSON body:
json
Copy code
{
"name": "Sample
Product",
"description": "This is a
test product.",
"price": 99.99
}
6.
Click Send to test the API.
7. Middleware for
Authentication (Optional)
To secure your APIs, you
can add middleware like auth:sanctum to routes:
php
Copy code
Route::middleware('auth:sanctum')->apiResource('products',
ProductController::class);
Summary
- Laravel
simplifies RESTful API development with Route::apiResource.
- CRUD
operations are implemented using controller methods.
- Use
Postman to test and debug APIs.
- Secure
APIs with middleware for authentication if needed.
Assignment
1.
Create a Category API following the same
process.
2.
Implement all CRUD operations for
categories.
3.
Test the APIs using Postman.
Comments
Post a Comment