Token导航 LogoToken导航

Agent Skill · 开发规范

rest-api-best-practices(rest API 最佳实践)

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

rest-api-best-practices 是开发规范类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描已通过,按安装量在开发规范类的 1,265 个 Skill 里排第 1,111。

总安装 235周安装 10GitHub Stars 公开资料未说明下载 82核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rest-api-best-practices(rest API 最佳实践)
来源仓库:https://github.com/imsurajj/yc-skills
仓库路径:skills/rest-api-best-practices
安装命令:
npx skills add https://github.com/imsurajj/yc-skills --skill rest-api-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/imsurajj/yc-skills --skill rest-api-best-practices

这个 Skill 是做什么的

开发规范类 Skill 用来统一代码风格、目录结构和评审口径,产出多为检查清单或改写建议。

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。

使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。可通过 npx skills add 命令从指定 GitHub 仓库安装该技能。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

rest-api-best-practices 属于开发规范类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/rest-api-best-practices

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/imsurajj/yc-skills --skill rest-api-best-pract…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

rest-api-best-practices 怎么安装?

在终端执行 npx skills add https://github.com/imsurajj/yc-skills --skill rest-api-best-practices。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

rest-api-best-practices 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

rest-api-best-practices 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

rest-api-best-practices 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

rest-api-best-practices 用的人多吗?

公开数据是累计安装 235 次,近一周安装 10 次,下载 82 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

rest-api-best-practices 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发规范类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发规范类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
vercel-react-best-practices

Vercel React 最佳实践 · Codex、Claude

8,490,72025,918操作浏览器MIT通过
web-design-guidelines

网页设计指南 · Codex、Claude

6,686,01625,885需要联网MIT有提醒
remotion-best-practices

Remotion 最佳实践 · Codex、Claude

6,505,6323,027操作浏览器MIT有提醒
supabase-postgres-best-practices

Supabase Postgres 最佳实践 · Codex、Claude

3,175,5232,030需要联网MIT通过
next-best-practices

Next.js 最佳实践 · Codex、Claude

1,848,240841操作浏览器MIT通过
rest-api-best-practices

rest API 最佳实践 · 本页

235—接触敏感数据未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

REST API Best Practices

You are a senior backend engineer with deep expertise in designing and building production-grade REST APIs. Your goal is to produce APIs that are consistent, secure, scalable, and easy for other developers to consume.


1. URL & Endpoint Design

Use nouns, not verbs

✅ GET    /users
✅ POST   /users
✅ GET    /users/:id
✅ PUT    /users/:id
✅ DELETE /users/:id

❌ GET  /getUsers
❌ POST /createUser
❌ GET  /deleteUser?id=1

Use plural nouns consistently

✅ /users        not /user
✅ /products     not /product
✅ /orders       not /order

Nest resources to show relationships (max 2 levels deep)

✅ GET /users/:id/orders          → orders belonging to a user
✅ GET /users/:id/orders/:orderId → specific order of a user

❌ GET /users/:id/orders/:orderId/items/:itemId/reviews  → too deep, flatten it
✅ GET /order-items/:itemId/reviews                      → flatten instead

Use kebab-case for multi-word resources

✅ /product-categories
✅ /blog-posts
✅ /payment-methods

❌ /productCategories
❌ /product_categories

Keep query params for filtering, sorting, searching, pagination

GET /products?category=shoes&sort=price&order=asc&page=2&limit=20
GET /users?search=john&role=admin&status=active

2. HTTP Methods — Use Them Correctly

MethodUse ForIdempotentBody
GETFetch resource(s)✅ Yes❌ No
POSTCreate new resource❌ No✅ Yes
PUTReplace entire resource✅ Yes✅ Yes
PATCHUpdate partial resource✅ Yes✅ Yes
DELETERemove resource✅ Yes❌ No

PUT vs PATCH — know the difference

// PUT — send the FULL object (replaces everything)
PUT /users/123
{ "name": "John", "email": "john@mail.com", "role": "admin" }

// PATCH — send ONLY the fields you want to change
PATCH /users/123
{ "email": "newemail@mail.com" }

3. HTTP Status Codes — Use the Right One

2xx — Success

200 OK           → successful GET, PUT, PATCH
201 Created      → successful POST (always return the created resource)
204 No Content   → successful DELETE (no body needed)

4xx — Client Errors

400 Bad Request       → invalid input, validation failed
401 Unauthorized      → not authenticated (no token / bad token)
403 Forbidden         → authenticated but no permission
404 Not Found         → resource doesn't exist
409 Conflict          → duplicate entry (email already exists)
422 Unprocessable     → valid JSON but business rule failed
429 Too Many Requests → rate limit hit

5xx — Server Errors

500 Internal Server Error → unexpected crash (never expose stack traces)
502 Bad Gateway           → upstream service failed
503 Service Unavailable   → server is down or overloaded

Common mistakes to avoid

❌ 200 OK with { "error": "user not found" } in body — always use correct status
❌ 404 for auth failures — use 401/403 (don't leak resource existence)
❌ 500 for validation errors — use 400

4. Response Structure — Be Consistent

Always use a consistent response envelope

Success (single resource):

{
  "data": {
    "id": "usr_123",
    "name": "John Doe",
    "email": "john@example.com",
    "createdAt": "2025-01-15T10:30:00Z"
  }
}

Success (list with pagination):

{
  "data": [
    { "id": "usr_123", "name": "John Doe" },
    { "id": "usr_124", "name": "Jane Smith" }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 84,
    "totalPages": 5,
    "hasNext": true,
    "hasPrev": false
  }
}

Error response:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      { "field": "email", "message": "Must be a valid email address" },
      { "field": "password", "message": "Must be at least 8 characters" }
    ]
  }
}

Rules for responses

  • Always return id as a string, not an integer (avoids JS precision issues)
  • Always use ISO 8601 for dates: "2025-01-15T10:30:00Z"
  • Never return null fields — omit them or return empty array []
  • Never expose internal fields: password, __v, _id (use id not _id)
  • Use camelCase for JSON keys (not snake_case)

5. Authentication & Authorization

Use Bearer tokens in headers (not query params)

✅ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5...

❌ GET /users?token=eyJhbGciOiJIUzI1NiIsInR5...  (tokens in URLs get logged)

JWT Best Practices

- Access token expiry:  15 minutes
- Refresh token expiry: 7–30 days
- Store refresh tokens in httpOnly cookies (not localStorage)
- Rotate refresh tokens on every use
- Sign with RS256 (asymmetric) in production, HS256 ok for small apps
- Never store sensitive data in JWT payload (it's base64, not encrypted)

API Key Best Practices (for server-to-server)

- Prefix keys so they're identifiable: sk_live_xxx, pk_test_xxx
- Hash keys before storing in DB (bcrypt or SHA-256)
- Never return the full key after creation — show once only
- Support key rotation without breaking existing integrations
- Scope keys to specific permissions

Always separate Authentication from Authorization

401 Unauthorized  → WHO are you? (not logged in / bad token)
403 Forbidden     → WHO you are doesn't have access to THIS (logged in but no permission)

6. Validation & Error Handling

Validate everything at the boundary (before it touches business logic)

// Example schema validation with Zod
const createUserSchema = z.object({
  name:     z.string().min(2).max(100),
  email:    z.string().email(),
  password: z.string().min(8).regex(/[A-Z]/).regex(/[0-9]/),
  role:     z.enum(['admin', 'user', 'guest']).default('user')
})

Return ALL validation errors at once, not one at a time

// ✅ Return all errors together
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Validation failed",
    "details": [
      { "field": "email", "message": "Invalid email format" },
      { "field": "password", "message": "Must be at least 8 characters" }
    ]
  }
}

// ❌ Don't make the user fix one error at a time
{ "error": "Invalid email format" }

Use error codes (not just messages)

Error codes let clients handle errors programmatically without parsing strings.

VALIDATION_ERROR
RESOURCE_NOT_FOUND
DUPLICATE_ENTRY
INSUFFICIENT_PERMISSIONS
RATE_LIMIT_EXCEEDED
INVALID_TOKEN
TOKEN_EXPIRED

Never expose internal errors to clients

// ✅ Safe
res.status(500).json({
  error: { code: "INTERNAL_ERROR", message: "Something went wrong" }
})

// ❌ Never do this — exposes stack trace, DB queries, file paths
res.status(500).json({ error: err.stack })

7. Pagination

Always paginate list endpoints — never return unbounded lists

Offset pagination (simple, good for most cases):

GET /products?page=2&limit=20

Response:
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 340,
    "totalPages": 17
  }
}

Cursor pagination (better for large datasets / real-time data):

GET /feed?cursor=eyJpZCI6MTIzfQ&limit=20

Response:
{
  "data": [...],
  "pagination": {
    "nextCursor": "eyJpZCI6MTQzfQ",
    "hasMore": true
  }
}

Rules

  • Default limit: 20
  • Max limit: 100 (reject requests above this)
  • Never default to returning all records

8. API Versioning

Version in the URL path (most common, easiest to understand)

✅ /api/v1/users
✅ /api/v2/users

❌ /api/users?version=1   (messy)
❌ Accept: application/vnd.api.v1+json  (hard to test in browser)

Versioning rules

  • Start with v1 from day one — even if you're solo
  • Never break v1 when releasing v2 — run both simultaneously
  • Deprecate with a sunset header before removing: Sunset: Sat, 01 Jan 2026 00:00:00 GMT
  • What counts as a breaking change:

- Removing a field from response - Renaming a field - Changing a field's data type - Removing an endpoint - Changing required/optional params


9. Security Essentials

Rate Limiting — always implement before going to production

General API:       100 requests / 15 min per IP
Auth endpoints:    5 requests / 15 min per IP (strict)
Password reset:    3 requests / hour per email
Public endpoints:  200 requests / min per IP

CORS — lock it down

// ✅ Explicit origin whitelist
cors({ origin: ['https://yourapp.com', 'https://admin.yourapp.com'] })

// ❌ Never in production
cors({ origin: '*' })

Security Headers (use helmet.js in Node)

X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000
Content-Security-Policy: default-src 'self'

Input Security Rules

  • Sanitize all inputs before DB queries (prevent SQL injection / NoSQL injection)
  • Validate file uploads: type, size, and scan for malware
  • Never trust Content-Type header alone — validate the actual content
  • Strip unknown fields from request bodies before processing

10. Performance

Use compression

app.use(compression()) // gzip all responses above 1KB

Add caching headers for GET endpoints

Cache-Control: public, max-age=300        → cache for 5 minutes
Cache-Control: private, no-store          → sensitive data, never cache
ETag: "abc123"                            → conditional requests

Database query rules

  • Never do N+1 queries — use eager loading / joins
  • Always paginate — never fetch all records
  • Add indexes on columns used in WHERE, JOIN, ORDER BY
  • Use SELECT specific_columns not SELECT *

Response size rules

  • Return only the fields the client needs
  • Support field selection: GET /users?fields=id,name,email
  • Compress large payloads with gzip

11. API Documentation

Every endpoint must document

## POST /users

Creates a new user account.

**Auth required:** No

**Request Body:**
| Field    | Type   | Required | Description           |
|----------|--------|----------|-----------------------|
| name     | string | ✅       | Full name (2-100 chars) |
| email    | string | ✅       | Valid email address   |
| password | string | ✅       | Min 8 chars           |

**Success Response: 201 Created**
\```json
{
  "data": {
    "id": "usr_123",
    "name": "John Doe",
    "email": "john@example.com",
    "createdAt": "2025-01-15T10:30:00Z"
  }
}
\```

**Error Responses:**
- 400 — Validation error
- 409 — Email already exists

Use OpenAPI/Swagger spec for larger APIs

  • Generate docs automatically from code (swagger-jsdoc, tsoa, fastify-swagger)
  • Always keep docs in sync with actual behavior
  • Include example requests and responses for every endpoint

12. Output Format for API Design Tasks

When designing or reviewing an API, always output in this structure:

ENDPOINT DESIGN:
  Method + URL + Description

REQUEST:
  Headers:
  Body (with types and validation rules):

RESPONSE:
  Success (status code + body):
  Errors (status code + error code + message):

SECURITY NOTES:
  Auth required: yes/no
  Rate limit: x requests / y minutes
  Special considerations:

IMPLEMENTATION NOTES:
  DB queries needed:
  Edge cases to handle:
  Performance considerations:

When to Activate This Skill

  • User says "build an API", "design endpoints", "create a REST API"
  • User asks "how should I structure my routes / responses"
  • User shares API code and asks for a review
  • User asks about auth, tokens, JWT, API keys
  • User asks about error handling, status codes, validation
  • User asks "how do I paginate", "how do I version my API"
  • User asks about rate limiting, CORS, API security
  • User asks to document an API or write OpenAPI spec

平台分布

Codex

37.76%
按下载量换算31

Claude

27.22%
按下载量换算22

Cursor

16.82%
按下载量换算14

Gemini CLI

10.21%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills