adding-api-docs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdd API Documentation (OpenAPI)
添加API文档(OpenAPI)
Use this skill when the user asks to add API docs, Swagger, OpenAPI spec, or generate endpoint documentation.
当用户要求添加API文档、Swagger、OpenAPI规范或生成端点文档时,使用此技能。
Steps
步骤
-
Detect the API framework — check for Express, Fastify, Next.js API routes, Hono, Django REST Framework, FastAPI, etc.
-
For Node.js/Express — installand
swagger-jsdoc:swagger-ui-expressbashnpm install swagger-jsdoc swagger-ui-express npm install -D @types/swagger-jsdoc @types/swagger-ui-expressCreate the OpenAPI spec from JSDoc annotations on route handlers:ts/** * @openapi * /api/users: * get: * summary: List all users * responses: * 200: * description: A list of users */ -
For Next.js API routes — create anfile manually or use
openapi.jsonto generate from route handlers. Serve the spec atnext-swagger-doc./api/docs -
For FastAPI (Python) — docs are built-in at(Swagger UI) and
/docs. Ensure Pydantic models are used for request/response types so schemas are auto-generated./redoc -
Add interactive docs UI — serve Swagger UI at aroute, or use Scalar/Redoc for a modern alternative:
/docsbashnpm install @scalar/express-api-reference -
Define schemas — create Zod schemas (or JSON Schema) for request bodies and responses, then reference them in the OpenAPI spec. For TypeScript projects, useto generate schemas from existing Zod validators.
zod-to-openapi -
Add authentication documentation — document the auth scheme (Bearer token, API key, OAuth2) in the OpenAPIsection.
securitySchemes
-
检测API框架 — 检查是否使用Express、Fastify、Next.js API路由、Hono、Django REST Framework、FastAPI等。
-
针对Node.js/Express — 安装和
swagger-jsdoc:swagger-ui-expressbashnpm install swagger-jsdoc swagger-ui-express npm install -D @types/swagger-jsdoc @types/swagger-ui-express从路由处理器上的JSDoc注释生成OpenAPI规范:ts/** * @openapi * /api/users: * get: * summary: List all users * responses: * 200: * description: A list of users */ -
针对Next.js API路由 — 手动创建文件,或使用
openapi.json从路由处理器生成。在next-swagger-doc路径提供规范。/api/docs -
针对FastAPI(Python) — 文档内置在(Swagger UI)和
/docs路径。确保使用Pydantic模型定义请求/响应类型,以便自动生成模式。/redoc -
添加交互式文档UI — 在路径提供Swagger UI,或使用Scalar/Redoc作为现代替代方案:
/docsbashnpm install @scalar/express-api-reference -
定义模式 — 为请求体和响应创建Zod模式(或JSON Schema),然后在OpenAPI规范中引用它们。对于TypeScript项目,使用从现有Zod验证器生成模式。
zod-to-openapi -
添加认证文档 — 在OpenAPI的部分记录认证方案(Bearer令牌、API密钥、OAuth2)。
securitySchemes
Notes
注意事项
- Keep the spec in sync with the actual API — generate from code when possible rather than maintaining a separate YAML file.
- Add example values to schemas for better developer experience.
- Version the API docs alongside the code.
- 保持规范与实际API同步 — 尽可能从代码生成,而非维护单独的YAML文件。
- 为模式添加示例值,提升开发者体验。
- 随代码一起对API文档进行版本控制。