File size: 3,420 Bytes
a7d7463 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | # REST API Design
## HTTP Methods
| Method | Purpose | Example |
|--------|---------|---------|
| GET | Retrieve data | `GET /users` |
| POST | Create new resource | `POST /users` |
| PUT | Replace entire resource | `PUT /users/1` |
| PATCH | Partial update | `PATCH /users/1` |
| DELETE | Remove resource | `DELETE /users/1` |
## URL Structure
```
https://api.example.com/v1/users/123/posts?page=1&limit=10
│ │ │ │ │
│ │ │ │ └── Query Parameters
│ │ │ └── Resource ID
│ │ └── Collection
│ └── Version
└── Base URL
```
## Status Codes
### Success
- `200 OK` - Request succeeded
- `201 Created` - Resource created
- `204 No Content` - Success, no body (DELETE)
### Client Errors
- `400 Bad Request` - Invalid input
- `401 Unauthorized` - Authentication required
- `403 Forbidden` - Authenticated but not permitted
- `404 Not Found` - Resource doesn't exist
- `422 Unprocessable Entity` - Validation error
### Server Errors
- `500 Internal Server Error` - Server error
- `502 Bad Gateway` - Gateway error
- `503 Service Unavailable` - Server down
## Best Practices
### Request
```http
GET /api/v1/users?status=active&sort=-created_at
Accept: application/json
Authorization: Bearer <token>
```
### Response
```json
{
"data": [
{
"id": 1,
"name": "John",
"email": "john@example.com"
}
],
"meta": {
"page": 1,
"per_page": 20,
"total": 100
},
"links": {
"self": "/api/v1/users?page=1",
"next": "/api/v1/users?page=2"
}
}
```
### Error Response
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}
```
## REST API Example (Node.js/Express)
### Basic Setup
```javascript
const express = require('express');
const app = express();
app.use(express.json());
// GET all users
app.get('/api/v1/users', (req, res) => {
res.json({ data: users });
});
// GET single user
app.get('/api/v1/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'Not found' });
res.json({ data: user });
});
// POST create user
app.post('/api/v1/users', (req, res) => {
const { name, email } = req.body;
// Validation
if (!name || !email) {
return res.status(400).json({ error: 'Missing fields' });
}
// Create
const newUser = { id: users.length + 1, name, email };
users.push(newUser);
res.status(201).json({ data: newUser });
});
// PUT update user
app.put('/api/v1/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'Not found' });
const { name, email } = req.body;
user.name = name || user.name;
user.email = email || user.email;
res.json({ data: user });
});
// DELETE user
app.delete('/api/v1/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: 'Not found' });
users.splice(index, 1);
res.status(204).send();
});
```
|