RESTful API (Representational State Transfer) 是一种基于 HTTP 协议的软件架构风格,用于构建网络应用程序接口。它遵循 REST 原则,通过 HTTP 方法 (GET, POST, PUT, DELETE 等) 对资源进行操作。
核心原则:
问题:如何安全地处理用户认证?
解决方案:
// Express 中使用 JWT 的示例
const jwt = require('jsonwebtoken');
const express = require('express');
const app = express();
app.post('/login', (req, res) => {
// 验证用户凭据
const user = { id: 1, username: 'test' };
const token = jwt.sign({ user }, 'your-secret-key', { expiresIn: '1h' });
res.json({ token });
});
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: 'Protected data' });
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, 'your-secret-key', (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
问题:API 升级时如何保持向后兼容?
解决方案:
/v1/users
)Accept: application/vnd.myapi.v1+json
)/users?version=1
)# Flask 中实现 URL 版本控制示例
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/v1/users')
def users_v1():
return jsonify({"version": "v1", "data": [...]})
@app.route('/v2/users')
def users_v2():
return jsonify({"version": "v2", "data": [...], "metadata": {...}})
问题:API 响应慢,如何处理?
解决方案:
// Spring Boot 中实现分页示例
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public ResponseEntity<Page<Product>> getProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("name"));
Page<Product> products = productRepository.findAll(pageable);
return ResponseEntity.ok(products);
}
}
问题:如何让开发者理解和使用 API?
解决方案:
# OpenAPI 示例 (Swagger)
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: Get all users
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
// 标准错误响应示例
{
"error": {
"code": "INVALID_REQUEST",
"message": "The request payload is invalid",
"details": [
{
"field": "email",
"issue": "Invalid email format"
}
]
}
}
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 中间件
app.use(bodyParser.json());
// 模拟数据库
let books = [
{ id: 1, title: 'Book 1', author: 'Author 1' },
{ id: 2, title: 'Book 2', author: 'Author 2' }
];
// 获取所有书籍
app.get('/api/books', (req, res) => {
res.json(books);
});
// 获取单个书籍
app.get('/api/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).json({ message: 'Book not found' });
res.json(book);
});
// 创建书籍
app.post('/api/books', (req, res) => {
const { title, author } = req.body;
if (!title || !author) {
return res.status(400).json({ message: 'Title and author are required' });
}
const newBook = {
id: books.length + 1,
title,
author
};
books.push(newBook);
res.status(201).json(newBook);
});
// 更新书籍
app.put('/api/books/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).json({ message: 'Book not found' });
const { title, author } = req.body;
if (!title || !author) {
return res.status(400).json({ message: 'Title and author are required' });
}
book.title = title;
book.author = author;
res.json(book);
});
// 删除书籍
app.delete('/api/books/:id', (req, res) => {
const bookIndex = books.findIndex(b => b.id === parseInt(req.params.id));
if (bookIndex === -1) return res.status(404).json({ message: 'Book not found' });
books.splice(bookIndex, 1);
res.status(204).send();
});
// 错误处理中间件
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
可以使用以下工具测试 API:
# cURL 示例
# 获取所有书籍
curl -X GET http://localhost:3000/api/books
# 创建新书籍
curl -X POST -H "Content-Type: application/json" -d '{"title":"New Book","author":"New Author"}' http://localhost:3000/api/books
# 更新书籍
curl -X PUT -H "Content-Type: application/json" -d '{"title":"Updated Book","author":"Updated Author"}' http://localhost:3000/api/books/1
# 删除书籍
curl -X DELETE http://localhost:3000/api/books/1
通过遵循 RESTful 原则和最佳实践,可以构建出高效、可维护且易于使用的 API,满足现代应用程序的需求。
没有搜到相关的文章