Learn RESTful Architecture and Build Your First API
REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API allows different applications to communicate with each other over HTTP using standard methods.
| Traditional Web App | REST API |
|---|---|
| Returns HTML pages | Returns JSON/XML data |
| Server-side rendering | Client-side rendering |
| Uses Blade templates | Returns raw data |
| Browser-specific | Platform-independent |
| Session-based | Token-based (stateless) |
REST APIs use standard HTTP methods to perform operations on resources. These methods correspond to CRUD (Create, Read, Update, Delete) operations.
| HTTP Method | CRUD Operation | Description | Example |
|---|---|---|---|
| GET | Read | Retrieve data (does not modify) | GET /api/posts - Get all posts GET /api/posts/1 - Get post #1 |
| POST | Create | Create new resource | POST /api/posts - Create new post |
| PUT | Update | Replace entire resource | PUT /api/posts/1 - Replace post #1 |
| PATCH | Update | Partially update resource | PATCH /api/posts/1 - Update some fields |
| DELETE | Delete | Remove resource | DELETE /api/posts/1 - Delete post #1 |
| Method | Safe | Idempotent | Has Body |
|---|---|---|---|
| GET | Yes | Yes | No |
| POST | No | No | Yes |
| PUT | No | Yes | Yes |
| PATCH | No | No | Yes |
| DELETE | No | Yes | No |
JSON (JavaScript Object Notation) is the standard data format for REST APIs. It's lightweight, human-readable, and supported by all programming languages.
{
"id": 1,
"title": "Introduction to REST APIs",
"content": "REST APIs are awesome...",
"author": "John Doe",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}
{
"data": [
{
"id": 1,
"title": "First Post",
"author": "John"
},
{
"id": 2,
"title": "Second Post",
"author": "Jane"
}
],
"total": 2,
"page": 1
}
{
"success": true,
"message": "Post created successfully",
"data": {
"id": 3,
"title": "New Post"
}
}
{
"success": false,
"message": "Validation failed",
"errors": {
"title": ["The title field is required"],
"content": ["The content must be at least 10 characters"]
}
}
HTTP status codes indicate the result of an API request. They help clients understand what happened without parsing the response body.
| Code | Category | Description | Usage |
|---|---|---|---|
| 200 | Success | OK | Successful GET, PUT, PATCH request |
| 201 | Success | Created | Resource successfully created (POST) |
| 204 | Success | No Content | Successful DELETE (no response body) |
| 400 | Client Error | Bad Request | Invalid request data/validation error |
| 401 | Client Error | Unauthorized | Authentication required |
| 403 | Client Error | Forbidden | Not authorized to access resource |
| 404 | Client Error | Not Found | Resource doesn't exist |
| 422 | Client Error | Unprocessable Entity | Validation errors |
| 500 | Server Error | Internal Server Error | Server crashed or exception occurred |
Laravel provides a separate routes/api.php file for API routes. All routes in this file are automatically prefixed with /api.
| routes/web.php | routes/api.php |
|---|---|
| For traditional web pages | For API endpoints |
| Returns HTML views | Returns JSON data |
| Uses sessions and cookies | Stateless (uses tokens) |
| CSRF protection enabled | CSRF protection disabled |
| URL: /posts | URL: /api/posts |
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Simple GET route - returns JSON
Route::get('/hello', function () {
return ['message' => 'Hello, World!'];
});
// GET route with parameter
Route::get('/users/{id}', function ($id) {
return [
'id' => $id,
'name' => 'John Doe',
'email' => 'john@example.com'
];
});
// POST route - receives data
Route::post('/posts', function (Request $request) {
return [
'success' => true,
'message' => 'Post created',
'data' => $request->all()
];
});
// Individual routes
Route::get('/posts', [PostController::class, 'index']); // List all
Route::post('/posts', [PostController::class, 'store']); // Create new
Route::get('/posts/{id}', [PostController::class, 'show']); // Show one
Route::put('/posts/{id}', [PostController::class, 'update']); // Update
Route::delete('/posts/{id}', [PostController::class, 'destroy']); // Delete
// OR use resource route (creates all routes above)
Route::apiResource('posts', PostController::class);
php artisan route:list to see all registered routes including API routes.
Edit routes/api.php:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// Test endpoint
Route::get('/test', function () {
return [
'status' => 'success',
'message' => 'API is working!',
'timestamp' => now()
];
});
// Get all students
Route::get('/students', function () {
return [
'data' => [
['id' => 1, 'name' => 'Alice', 'grade' => 'A'],
['id' => 2, 'name' => 'Bob', 'grade' => 'B'],
['id' => 3, 'name' => 'Charlie', 'grade' => 'A']
],
'total' => 3
];
});
// Get single student by ID
Route::get('/students/{id}', function ($id) {
$students = [
1 => ['id' => 1, 'name' => 'Alice', 'grade' => 'A', 'email' => 'alice@example.com'],
2 => ['id' => 2, 'name' => 'Bob', 'grade' => 'B', 'email' => 'bob@example.com'],
3 => ['id' => 3, 'name' => 'Charlie', 'grade' => 'A', 'email' => 'charlie@example.com']
];
if (isset($students[$id])) {
return $students[$id];
}
return response()->json([
'error' => 'Student not found'
], 404);
});
// Create new student
Route::post('/students', function (Request $request) {
// Validate incoming data
$validated = $request->validate([
'name' => 'required|string|max:255',
'grade' => 'required|string|max:2',
'email' => 'required|email'
]);
// In real app, save to database
// For now, just return the data with fake ID
return response()->json([
'success' => true,
'message' => 'Student created successfully',
'data' => [
'id' => rand(4, 100),
'name' => $validated['name'],
'grade' => $validated['grade'],
'email' => $validated['email'],
'created_at' => now()
]
], 201); // 201 = Created
});
// Success with 200 OK
return response()->json($data, 200);
// Created with 201 Created
return response()->json($data, 201);
// Not found with 404
return response()->json(['error' => 'Not found'], 404);
// Validation error with 422
return response()->json(['errors' => $errors], 422);
// Server error with 500
return response()->json(['error' => 'Server error'], 500);
Postman is a popular tool for testing APIs. It allows you to send HTTP requests and view responses without writing any code.
http://localhost:8000/api/studentshttp://localhost:8000/api/students{
"name": "David",
"grade": "A",
"email": "david@example.com"
}
http://localhost:8000/api/students
| Action | HTTP Method | URL Pattern | Example |
|---|---|---|---|
| List all | GET | /api/resources | GET /api/posts |
| Get one | GET | /api/resources/{id} | GET /api/posts/5 |
| Create | POST | /api/resources | POST /api/posts |
| Update | PUT/PATCH | /api/resources/{id} | PUT /api/posts/5 |
| Delete | DELETE | /api/resources/{id} | DELETE /api/posts/5 |
// Pagination
GET /api/posts?page=2&per_page=10
// Filtering
GET /api/posts?status=published&category=laravel
// Sorting
GET /api/posts?sort_by=created_at&order=desc
// Searching
GET /api/posts?search=rest+api
// Multiple filters
GET /api/posts?author=john&status=published&sort=latest
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
// In-memory data store (array)
$books = [
['id' => 1, 'title' => 'Laravel Basics', 'author' => 'John Doe', 'price' => 29.99],
['id' => 2, 'title' => 'REST API Guide', 'author' => 'Jane Smith', 'price' => 34.99],
['id' => 3, 'title' => 'PHP Mastery', 'author' => 'Bob Johnson', 'price' => 39.99],
];
// GET /api/books - List all books
Route::get('/books', function () use ($books) {
return response()->json([
'success' => true,
'data' => $books,
'total' => count($books)
], 200);
});
// GET /api/books/{id} - Get single book
Route::get('/books/{id}', function ($id) use ($books) {
foreach ($books as $book) {
if ($book['id'] == $id) {
return response()->json([
'success' => true,
'data' => $book
], 200);
}
}
return response()->json([
'success' => false,
'message' => 'Book not found'
], 404);
});
// POST /api/books - Create new book
Route::post('/books', function (Request $request) {
// Validate request data
$validated = $request->validate([
'title' => 'required|string|max:255',
'author' => 'required|string|max:255',
'price' => 'required|numeric|min:0'
]);
// Create new book (in real app, save to database)
$newBook = [
'id' => rand(4, 1000),
'title' => $validated['title'],
'author' => $validated['author'],
'price' => $validated['price'],
'created_at' => now()->toDateTimeString()
];
return response()->json([
'success' => true,
'message' => 'Book created successfully',
'data' => $newBook
], 201);
});
Requirements:
In Day 2, we'll learn about: