Restful Api Advance
## Authentication and Authorization
### JWT (JSON Web Token) Authentication
JWT is like a "digital ID card" that contains user identity information and can verify its authenticity.
// JWT Structure
// Header.Payload.Signature
// Login Flow
POST /api/auth/login
{
"email": "user@example.com",
"password": "password123"
}
// Response
{
"success": true,
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": 123,
"name": "Zhang San",
"email": "user@example.com"
}
}
}
// Subsequent requests carry Token
GET /api/users/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
### OAuth 2.0 Integration
// Third-party login flow
GET /api/auth/google/redirect
// Redirect to Google authorization page
// Callback handling
GET /api/auth/google/callback?code=authorization_code
// Return application Token
API Rate Limiting and Quotas
Request Rate Limiting
// Response headers contain rate limit info
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
// 1000 requests per hour limit
X-RateLimit-Remaining: 999
// Remaining requests
X-RateLimit-Reset: 1642694400
// Reset timestamp
// Response when limit exceeded
HTTP/1.1 429 Too Many Requests
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests, please try again later",
"retryAfter": 3600
// Recommended wait time (seconds)
}
}
* * *
## Data Caching Strategy
### HTTP Cache Headers
// Set cache strategy
GET /api/users/123
Cache-Control: public, max-age=3600
// Cache for 1 hour
ETag: "a1b2c3d4e5f6"
// Resource version identifier
// Conditional request
GET /api/users/123
If-None-Match: "a1b2c3d4e5f6"
// If resource hasn't changed
HTTP/1.1 304 Not Modified
### Redis Cache Example
// Cache strategy pseudocode
async function getUser(userId) {
// 1. Check cache first
const cached = await redis.get(`user:${userId}`);
if (cached) {
return JSON.parse(cached);
}
// 2. Cache miss, query database
const user = await database.findUser(userId);
// 3. Cache the result
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
return user;
}
* * *
## APIs in Microservices Architecture
### Inter-service Communication
### API Gateway Pattern
// API Gateway routing configuration
{
"routes": [
{
"path": "/api/users/*",
"service": "user-service",
"url": "http://user-service:3001"
},
{
"path": "/api/orders/*",
"service": "order-service",
"url": "http://order-service:3002"
}
]
}
* * *
## GraphQL vs REST
### Limitations of REST API
// REST: Need multiple requests to get related data
GET /api/users/123
// Get user information
GET /api/users/123/posts
// Get user's posts
GET /api/posts/456/comments
// Get post comments
### Advantages of GraphQL
// GraphQL: Get required data in one request
query {
user(id: 123) {
name
email
posts {
title
comments {
content
author
}
}
}
}
YouTip