restful api 设计的核心是围绕资源组织,使用标准 http 方法操作资源。1. 资源命名应使用名词,uri 使用斜杠分隔层级,避免扩展名,使用连字符提高可读性;2. http 方法对应操作:get 获取、post 创建、put 更新、delete 删除;3. 使用合适状态码如 200 成功、404 未找到等;4. 版本控制通过 uri 或请求头实现;5. hateoas 提供动态发现能力;6. 过滤排序使用查询参数,如 /users?name=john;7. 安全方面采用身份验证(如 jwt)、授权(如 rbac)、https、输入验证和速率限制;8. 文档使用 openapi 等标准化格式,提供详细描述和示例代码,并保持更新。
RESTful API 设计,简单来说,就是让你的 API 看起来更像一个网站,资源有唯一的地址,用标准的方法(GET、POST、PUT、DELETE)来操作。关键在于“资源”和“状态转移”。
RESTful API 设计的核心在于围绕资源进行组织。每个资源都应该有一个唯一的 URI,并且客户端可以通过标准的 HTTP 方法来操作这些资源。
对于列表资源的过滤和排序,可以使用查询参数。例如:
需要注意的是,对于复杂的过滤条件,可能需要考虑使用更高级的查询语言,例如 GraphQL。
安全性是 API 设计中非常重要的一环。以下是一些常见的安全措施:
例如,使用 JWT 的一个简单示例 (Python + Flask):
import jwt import datetime from functools import wraps from flask import Flask, request, jsonify, make_response app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' # 实际应用中应使用更强的密钥 def token_required(f): @wraps(f) def decorated(*args, **kwargs): token = request.headers.get('Authorization') if not token: return jsonify({'message': 'Token is missing!'}), 401 try: data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"]) # 在这里可以根据 data['user'] 查询用户信息,并传递给被装饰的函数 except: return jsonify({'message': 'Token is invalid!'}), 401 return f(*args, **kwargs) return decorated @app.route('/login') def login(): auth = request.authorization if not auth or not auth.username or not auth.password: return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) # 在这里验证用户名和密码 if auth.username == 'test' and auth.password == 'password': token = jwt.encode({ 'user': auth.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) }, app.config['SECRET_KEY'], algorithm="HS256") return jsonify({'token': token}) return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) @app.route('/protected') @token_required def protected(): return jsonify({'message': 'This is a protected route!'}) if __name__ == '__main__': app.run(debug=True)
清晰、完整的 API 文档对于 API 的使用者来说至关重要。以下是一些建议:
例如,使用 Swagger 的一个简单示例 (YAML):
openapi: 3.0.0 info: title: User API version: v1 paths: /users: get: summary: Get all users responses: '200': description: Successful operation content: application/json: schema: type: array items: type: object properties: id: type: integer name: type: string /users/{id}: get: summary: Get a user by ID parameters: - name: id in: path required: true schema: type: integer responses: '200': description: Successful operation content: application/json: schema: type: object properties: id: type: integer name: type: string
这个 YAML 文件可以被 Swagger UI 解析,生成交互式的 API 文档。
总而言之,RESTful API 设计不仅仅是一种技术规范,更是一种设计哲学。它强调资源的重要性,并通过标准的 HTTP 方法来操作这些资源。一个好的 RESTful API 应该易于理解、易于使用、易于维护,并且具有良好的安全性。
以上就是RESTful API设计规范详细解析与示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号