How to Create API in Laravel: Simple Steps and Example
To create an API in Laravel, define API routes in
routes/api.php, create a controller with methods returning JSON responses, and use Laravel's routing to connect them. Use php artisan make:controller to generate controllers and return data with response()->json().Syntax
In Laravel, API routes are defined in routes/api.php. Controllers handle the logic and return JSON responses. Use Route::get/post/put/delete to define endpoints. Controllers use methods like response()->json() to send data.
- routes/api.php: Define API endpoints.
- Controller: Contains methods to process requests.
- response()->json(): Sends JSON data as API response.
php
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::get('/items', [ItemController::class, 'index']); // Controller method example public function index() { return response()->json(['items' => ['item1', 'item2']]); }
Example
This example shows how to create a simple API endpoint that returns a list of items in JSON format. It includes route definition and controller code.
php
<?php // routes/api.php use Illuminate\Support\Facades\Route; use App\Http\Controllers\ItemController; Route::get('/items', [ItemController::class, 'index']); // app/Http/Controllers/ItemController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class ItemController extends Controller { public function index() { $items = ['apple', 'banana', 'cherry']; return response()->json(['items' => $items]); } }
Output
{"items":["apple","banana","cherry"]}
Common Pitfalls
Common mistakes when creating APIs in Laravel include:
- Defining API routes in
web.phpinstead ofapi.php, which can cause session or CSRF issues. - Not returning JSON responses, causing clients to receive HTML or unexpected data.
- Forgetting to import controller classes or using incorrect namespaces.
- Not using proper HTTP methods (GET, POST, etc.) for API routes.
php
<?php // Wrong: Defining API route in web.php Route::get('/items', function() { return ['apple', 'banana']; // returns array, Laravel automatically converts to JSON response }); // Right: Defining API route in api.php with JSON response use App\Http\Controllers\ItemController; Route::get('/items', [ItemController::class, 'index']);
Quick Reference
| Step | Description |
|---|---|
| Define routes | Add API routes in routes/api.php using Route facade. |
| Create controller | Use php artisan make:controller to create controller. |
| Write methods | Add methods that return JSON with response()->json(). |
| Test API | Use tools like Postman or browser to test endpoints. |
Key Takeaways
Define API routes in routes/api.php to separate API logic from web routes.
Create controllers with methods that return JSON responses using response()->json().
Use correct HTTP methods and namespaces to avoid routing and response issues.
Test your API endpoints with tools like Postman to ensure correct output.