Restful Api Practices
## Security Best Practices
### 1. Authentication and Authorization
```javascript
// Use JWT Token for authentication
GET /api/users/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
// API response includes user permission check
{
"success": true,
"data": {
"id": 123,
"name": "Zhang San",
"role": "user"
}
}
### 2. Input Validation
```json
// Server-side validation example
POST /api/users
{
"email": "test@example.com",
"password": "123" // Password too short
}
// Validation failed response
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Password must be at least 8 characters"
}
}
### 3. HTTPS and Data Encryption
* β
https://api.example.com/users
* β http://api.example.com/users
* * *
## Performance Optimization Practices
### 1. Data Pagination
```json
// Avoid returning too much data at once
GET /api/users?page=1&limit=20
{
"success": true,
"data": [...], // Only return 20 records
"pagination": {
"currentPage": 1,
"totalPages": 50,
"totalItems": 1000
}
}
### 2. Field Filtering
```json
// Only return required fields
GET /api/users?fields=id,name,email
{
"success": true,
"data": [
{
"id": 1,
"name": "Zhang San",
"email": "zhangsan@example.com"
// Other unnecessary fields are not returned
}
]
}
### 3. Caching Strategy
```http
// Use cache headers
GET /api/users/123
Cache-Control: max-age=3600 // Cache for 1 hour
// Conditional request
GET /api/users/123
If-None-Match: "etag-value"
// 304 Not Modified (data has not changed)
* * *
## Error Handling Best Practices
### Unified Error Format
```json
{
"success": false,
"error": {
"code": "SPECIFIC_ERROR_CODE", // Machine-readable error code
"message": "User-friendly error message", // Human-readable error information
"details": {...}, // Detailed error information (optional)
"timestamp": "2024-01-15T10:00:00Z"
}
}
### Common Error Code Design
```javascript
const ERROR_CODES = {
// 4xx Client errors
'VALIDATION_ERROR': 400, // Data validation failed
'UNAUTHORIZED': 401, // Unauthorized
'FORBIDDEN': 403, // Access forbidden
'NOT_FOUND': 404, // Resource not found
'METHOD_NOT_ALLOWED': 405, // Method not allowed
'CONFLICT': 409, // Resource conflict
// 5xx Server errors
'INTERNAL_ERROR': 500, // Internal server error
'SERVICE_UNAVAILABLE': 503 // Service unavailable
}
* * *
## API Documentation
### Using Standard Documentation Format
Recommended to use OpenAPI (Swagger) specification:
```yaml
# swagger.yaml example
openapi: 3.0.0
info:
title: User Management API
version: 1.0.0
description: Provides user CRUD operations
paths:
/api/users:
get:
summary: Get user list
parameters:
- name: page
in: query
description: Page number
schema:
type: integer
default: 1
responses:
'200':
description: Success
content:
application/json:
schema:
type: object
properties:
success:
type: boolean
data:
type: array
items:
$ref: '#/components/schemas/User'
* * *
## Version Control Strategy
### URL Version Control (Recommended)
```http
// Version 1
GET /api/v1/users
// Version 2 (new fields, backward compatible)
GET /api/v2/users
{
"id": 1,
"name": "Zhang San",
"email": "zhangsan@example.com",
"avatar": "https://example.com/avatar.jpg" // New field
}
### Compatibility Handling
```json
// Backward compatible strategy
{
"deprecationWarning": "This API version will be discontinued after June 1, 2024. Please upgrade to v2",
"data": {...}
}
## Practice Exercises
### Exercise 1: Book Management System API
Design a simple book management system with the following features:
#### Requirements Analysis
* Manage book information (title, author, ISBN, price)
* Manage book categories
* Support CRUD operations for books
* Support filtering books by category
#### API Design Exercise
**Please design the following API endpoints**:
```http
// Your task: complete the following API design
// Book related
GET /api/books // Get book list
GET /api/books/{id} // Get specific book
POST /api/books // Create new book
PUT /api/books/{id} // Update book information
DELETE /api/books/{id} // Delete book
// Category related
GET /api/categories // Get category list
GET /api/categories/{id}/books // Get books under category
Example data structure:
```json
{
"id": 1,
"title": "Professional JavaScript",
"author": "Nicholas C. Zakas",
"isbn": "9787115275790",
"price": 99.00,
"categoryId": 1,
"category": {
"id": 1,
"name": "Programming Technology"
},
"publishedDate": "2012-03-01",
"description": "In-depth understanding of JavaScript",
"stock": 50
}
#### Exercise Tasks
1. **Design API Documentation**: Write detailed request and response examples for each endpoint
2. **Error Handling**: Design response formats for various error scenarios
3. **Data Validation**: List validation rules for each field
4. **Test Cases**: Write curl commands to test each API
### Exercise 2: Todo API
Create a todo item management API:
#### Functional Requirements
* Create, view, update, delete todo items
* Mark task completion status
* Filter tasks by status
* Support task priority
#### Data Model Design
```json
{
"id": 1,
"title": "Learn RESTful API",
"description": "Complete the API tutorial learning",
"status": "pending", // pending, completed, cancelled
"priority": "high", // low, medium, high
"dueDate": "2024-01-20",
"createdAt": "2024-01-15T08:00:00Z",
"updatedAt": "2024-01-15T08:00:00Z"
}
#### Challenge Tasks
1. **Batch Operations**: Design API for batch updating task status
2. **Search Functionality**: Support searching by title and description
3. **Statistics**: Return task completion statistics
### Exercise 3: Social Media API
Design a simplified social media platform API:
#### Core Features
* User registration and login
* Post and view updates
* Follow other users
* Like and comment
#### API Structure Design
```http
// User related
POST /api/auth/register // User registration
POST /api/auth/login // User login
GET /api/users/profile // Get personal profile
// Post related
GET /api/posts // Get post list
POST /api/posts // Create new post
GET /api/posts/{id} // Get specific post
DELETE /api/posts/{id} // Delete post
// Interaction related
POST /api/posts/{id}/like // Like post
POST /api/posts/{id}/comments // Add comment
GET /api/posts/{id}/comments // Get
YouTip