Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Advanced RESTful API

Advanced RESTful API

Authentication and authorization

JWT (JSON Web Token) authentication

A JWT is like a "digital ID card" that contains the user's identity information and can be verified for authenticity.

// JWT 的结构

// Header.Payload.Signature



// Login process

POST /api/auth/login

{

  "email": "user@example.com",

  "password": "password123"

}



// 响应

{

  "success": true,

  "data": {

    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",

    "user": {

      "id": 123,

      "name": "张三",

      "email": "user@example.com"

    }

  }

}



// Subsequent requests carry Token

GET /api/users/profile

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

OAuth 2.0 integration

// 第三方登录流程

GET /api/auth/google/redirect

// Redirect to Google authorization page



// Callback handling

GET /api/auth/google/callback?code=authorization_code

// Return application Token

API 限流和配额

请求频率限制

javascript// 响应头中包含限流信息

HTTP/1.1 200 OK

X-RateLimit-Limit: 1000        // 每小时限制1000次请求

X-RateLimit-Remaining: 999     // 剩余请求次数

X-RateLimit-Reset: 1642694400  // 重置时间戳



// Response when exceeding limits

HTTP/1.1 429 Too Many Requests

{

  "success": false,

  "error": {

    "code": "RATE_LIMIT_EXCEEDED",

    "message": "请求过于频繁,请稍后再试",

    "retryAfter": 3600  // 建议等待时间(秒)

  }

}


Data caching strategy

HTTP cache headers

// 设置缓存策略

GET /api/users/123

Cache-Control: public, max-age=3600  // 缓存1小时

ETag: "a1b2c3d4e5f6"                // 资源版本标识



// Conditional request

GET /api/users/123

If-None-Match: "a1b2c3d4e5f6"



// If resources have not changed

HTTP/1.1 304 Not Modified

Redis caching example

// 缓存策略伪代码

async function getUser(userId) {

  // 1. First check cache

  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 results

  await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));

  

  return user;

}


APIs in a microservices architecture

Inter-service communication

API gateway pattern

// API 网关路由配置

{

  "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: 需要多次请求获取相关数据

GET /api/users/123        // 获取用户信息

GET /api/users/123/posts  // 获取用户发布的文章

GET /api/posts/456/comments // 获取文章评论

Advantages of GraphQL

// GraphQL: 一次请求获取所需数据

query {

  user(id: 123) {

    name

    email

    posts {

      title

      comments {

        content

        author

      }

    }

  }

}