{% extends "admin/base.html" %} {% load i18n static %} {% block title %}{{ title }} - {{ site_header }}{% endblock %} {% block extrastyle %} {{ block.super }} {% endblock %} {% block breadcrumbs %} {% endblock %} {% block content %}

📖 API 使用帮助

本页面提供完整的 API 文档,包括端点说明、认证流程、请求响应示例和错误处理。

🔐 认证流程

API 使用 JWT (JSON Web Token) 进行认证。访问受保护的端点需要在请求头中包含令牌。

1. 获取令牌

获取访问令牌 页面生成您的个人令牌。

2. 在请求中使用令牌

Authorization: Bearer YOUR_ACCESS_TOKEN

3. 令牌过期处理

Access Token 过期后,使用 Refresh Token 获取新令牌:

curl -X POST "https://example.com/api/auth/token/refresh/" \ -H "Content-Type: application/json" \ -d '{"refresh": "YOUR_REFRESH_TOKEN"}'

📡 API 端点

端点 方法 认证 描述
/api/posts/ GET POST 需要 列出所有文章 / 创建新文章
/api/posts/{id}/ GET PUT PATCH DELETE 需要 获取 / 更新 / 删除单篇文章
/api/categories/ GET 列出所有分类
/api/tags/ GET 列出所有标签
/api/auth/token/ POST 获取 JWT 令牌(用户名密码)
/api/auth/token/refresh/ POST 刷新 JWT 令牌
/api/auth/token/verify/ POST 验证 JWT 令牌
/api/health/ GET 服务存活 + DB ping(200 / 503,Cache-Control: no-store
/api/me/ GET 需要 身份自检:{id, username, email, is_staff, token_exp}token_exp ISO-8601)

💻 请求示例

获取文章列表

curl -X GET "https://example.com/api/posts/" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

获取单篇文章

curl -X GET "https://example.com/api/posts/1/" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

创建文章

curl -X POST "https://example.com/api/posts/" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "title": "文章标题", "content": "文章内容...", "status": "published" }'

更新文章

curl -X PATCH "https://example.com/api/posts/1/" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"title": "更新后的标题"}'

删除文章

curl -X DELETE "https://example.com/api/posts/1/" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

健康检查(无需令牌)

curl -X GET "https://example.com/api/health/" # 200 OK:{"version":"1.0","status":"ok","db":"ok","django_version":"3.2.x","timestamp":"..."} # 503 :{"version":"1.0","status":"degraded","db":"error",...}

身份自检(验证令牌是否可用)

curl -X GET "https://example.com/api/me/" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" # {"version":"1.0","id":1,"username":"admin","email":"...","is_staff":true,"token_exp":"2026-06-02T12:34:56+00:00"}

📦 响应格式

所有响应均为 JSON 格式。

成功响应

{ "id": 1, "title": "文章标题", "content": "文章内容...", "author": { "id": 1, "username": "admin", "email": "admin@example.com" }, "status": "published", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-01T00:00:00Z" }

分页响应

{ "count": 100, "next": "https://example.com/api/posts/?page=2", "previous": null, "results": [...] }

错误响应

{ "detail": "Authentication credentials were not provided." }

⚠️ 错误码

401 Unauthorized 未提供认证凭证或令牌已过期
403 Forbidden 无权执行此操作
404 Not Found 请求的资源不存在
503 Service Unavailable 服务不可用(如数据库失联,详见 /api/health/
500 Server Error 服务器内部错误

🔗 快速链接

{% endblock %}