Token导航 LogoToken导航

Agent Skill · 研究检索

afrexai-api-architect(afrexai API 架构师)

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

afrexai-api-architect 是研究检索类 Agent Skill,可用宿主为 OpenClaw,通过ClawHub获取,权限为接触敏感数据;许可证为 MIT-0,第三方扫描有提醒项,按安装量在研究检索类的 73,675 个 Skill 里排第 6,150。

总安装 23,163周安装 928GitHub Stars 公开资料未说明下载 7,498核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

请帮我安装这个 Agent Skill:afrexai-api-architect(afrexai API 架构师)
来源仓库:https://github.com/1kalin/afrexai-api-architect
安装命令:
openclaw skills install afrexai-api-architect
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

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

ClawHubOpenClaw
openclaw skills install afrexai-api-architect

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

Afrexai API Architect 设计端到端的生产级 API 架构,包括鉴权与安全策略。适用于微服务集成、前后端协作及接口文档自动生成场景。支持 OpenAPI 规范草稿生成与错误码标准化,提升团队协作效率。字段命名与业务语义需与现有代码库对齐,禁止虚构未实现的 endpoint。

部署前应在沙箱环境验证鉴权逻辑,防止越权访问关键数据。

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

    可以直接复制的命令是 openclaw skills install afrexai-api-architect;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

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

常见问题

6 条

afrexai-api-architect 怎么安装?

在终端执行 openclaw skills install afrexai-api-architect。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

afrexai-api-architect 支持哪些 AI 工具?

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

afrexai-api-architect 需要什么权限?

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

afrexai-api-architect 是免费的吗?

来源标注的许可证是 MIT-0。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

afrexai-api-architect 用的人多吗?

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

afrexai-api-architect 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

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

值得选的地方

  • 专注 OpenClaw 一种宿主,触发方式和使用习惯不用来回切换。
  • 许可证明确为 MIT-0,商用和分发边界好判断。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 OpenClaw,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
afrexai-api-architect

afrexai API 架构师 · 本页

23,163—接触敏感数据MIT-0有提醒

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

SKILL.md 原文

name
afrexai-api-architect
description
Design, build, test, document, and secure production-grade APIs. Covers the full lifecycle from schema design through deployment, monitoring, and versioning. Use when designing new APIs, reviewing existing ones, generating OpenAPI specs, building test suites, or debugging production issues.
metadata
{"openclaw":{"os":["linux","darwin","win32"]}}

API Architect — Full Lifecycle API Development

Design, build, test, document, secure, and monitor production-grade APIs. Not just curl commands — a complete engineering methodology.

When to Use

  • Designing a new API (REST, GraphQL, or gRPC)
  • Reviewing an existing API for quality, consistency, or security
  • Generating or validating OpenAPI/Swagger specs
  • Building comprehensive test suites (unit, integration, contract, load)
  • Debugging production API issues
  • Planning API versioning and deprecation
  • Setting up monitoring, rate limiting, and error handling

Phase 1: API Design

Design-First Approach

Always design before coding. The spec IS the contract.

Resource Modeling

Map your domain to resources using this template:

# api-design.yaml
service: order-management
base_path: /api/v1
resources:
  - name: orders
    path: /orders
    description: Customer purchase orders
    identifier: order_id (UUID)
    parent: null
    operations: [list, create, get, update, cancel]
    sub_resources:
      - name: line_items
        path: /orders/{order_id}/items
        operations: [list, add, update, remove]
      - name: payments
        path: /orders/{order_id}/payments
        operations: [list, create, get, refund]
    states: [draft, confirmed, processing, shipped, delivered, cancelled]
    transitions:
      - from: draft → to: confirmed (action: confirm)
      - from: confirmed → to: processing (action: process)
      - from: processing → to: shipped (action: ship)
      - from: shipped → to: delivered (action: deliver)
      - from: [draft, confirmed] → to: cancelled (action: cancel)
Naming Conventions Checklist
RuleGoodBad
Plural nouns for collections/users/user, /getUsers
Kebab-case for multi-word/line-items/lineItems, /line_items
No verbs in URLsPOST /orders/createOrder
Nest for ownership/users/123/orders/orders?user=123 (for primary relationship)
Max 3 levels deep/users/123/orders/users/123/orders/456/items/789/options
Filter via query params/orders?status=active/active-orders
Actions as sub-resourcePOST /orders/123/cancelPATCH /orders/123 {cancelled:true}
HTTP Methods — Decision Matrix
Need to...                          → Method   Idempotent?  Safe?
Get a resource or collection        → GET      Yes          Yes
Create a new resource               → POST     No           No
Full replace of a resource          → PUT      Yes          No
Partial update of a resource        → PATCH    No*          No
Remove a resource                   → DELETE   Yes          No
Check if resource exists            → HEAD     Yes          Yes
List allowed methods                → OPTIONS  Yes          Yes

* PATCH can be idempotent if using JSON Merge Patch
Status Code Decision Tree
Success?
├── Created something new? → 201 Created (Location header)
├── Accepted for async processing? → 202 Accepted (include status URL)
├── No body to return? → 204 No Content
└── Returning data? → 200 OK

Client error?
├── Malformed request syntax? → 400 Bad Request
├── No/invalid credentials? → 401 Unauthorized
├── Valid credentials but insufficient permissions? → 403 Forbidden
├── Resource doesn't exist? → 404 Not Found
├── Method not allowed on resource? → 405 Method Not Allowed
├── Conflict with current state? → 409 Conflict
├── Resource permanently gone? → 410 Gone
├── Validation failed? → 422 Unprocessable Entity
├── Too many requests? → 429 Too Many Requests (Retry-After header)
└── Precondition failed (etag mismatch)? → 412 Precondition Failed

Server error?
├── Unexpected failure? → 500 Internal Server Error
├── Upstream dependency failed? → 502 Bad Gateway
├── Temporarily overloaded? → 503 Service Unavailable (Retry-After)
└── Upstream timeout? → 504 Gateway Timeout

Request/Response Design

Standard Response Envelope
// Success (single resource)
{
  "data": { "id": "ord_abc123", "status": "confirmed", ... },
  "meta": { "request_id": "req_xyz789" }
}

// Success (collection)
{
  "data": [ ... ],
  "meta": { "request_id": "req_xyz789" },
  "pagination": {
    "total": 142,
    "page": 2,
    "per_page": 20,
    "total_pages": 8,
    "next": "/api/v1/orders?page=3&per_page=20",
    "prev": "/api/v1/orders?page=1&per_page=20"
  }
}

// Error
{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "Request validation failed",
    "details": [
      { "field": "email", "message": "Must be a valid email address", "code": "INVALID_FORMAT" },
      { "field": "age", "message": "Must be at least 18", "code": "MIN_VALUE", "min": 18 }
    ]
  },
  "meta": { "request_id": "req_xyz789" }
}
Pagination Patterns — When to Use Which
PatternUse WhenProsCons
Offset ?page=2&per_page=20Simple UI pagination, small datasetsEasy to implement, page jumpingDrift on inserts, slow on large offsets
Cursor ?after=eyJ...&limit=20Infinite scroll, real-time feeds, large datasetsConsistent, performantNo page jumping, opaque cursors
Keyset ?created_after=2024-01-01&limit=20Time-series data, logsFast, transparentRequires sortable field, no count
Filtering, Sorting, Field Selection
# Filtering
GET /orders?status=active&created_after=2024-01-01&total_min=100

# Sorting (prefix - for descending)
GET /orders?sort=-created_at,total

# Field selection (reduce payload)
GET /orders?fields=id,status,total,customer.name

# Search
GET /products?q=wireless+headphones

# Combined
GET /orders?status=active&sort=-created_at&fields=id,status,total&page=1&per_page=10

Phase 2: OpenAPI Specification

Generate OpenAPI 3.1 Spec

For each resource in your design, generate a complete spec:

openapi: 3.1.0
info:
  title: Order Management API
  version: 1.0.0
  description: |
    Order lifecycle management.
    
    ## Authentication
    All endpoints require Bearer token authentication.
    
    ## Rate Limits
    - Standard: 100 req/min
    - Bulk operations: 10 req/min
  contact:
    name: API Support
    email: api@example.com
  license:
    name: MIT
servers:
  - url: https://api.example.com/v1
    description: Production
  - url: https://staging-api.example.com/v1
    description: Staging

paths:
  /orders:
    get:
      operationId: listOrders
      summary: List orders
      tags: [Orders]
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/PerPageParam'
        - name: status
          in: query
          schema:
            $ref: '#/components/schemas/OrderStatus'
        - name: created_after
          in: query
          schema:
            type: string
            format: date-time
      responses:
        '200':
          description: Order list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderListResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'

    post:
      operationId: createOrder
      summary: Create an order
      tags: [Orders]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateOrderRequest'
            examples:
              basic:
                summary: Basic order
                value:
                  customer_id: "cust_abc"
                  items:
                    - product_id: "prod_xyz"
                      quantity: 2
      responses:
        '201':
          description: Order created
          headers:
            Location:
              schema:
                type: string
              description: URL of created order
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OrderResponse'
        '422':
          $ref: '#/components/responses/ValidationError'

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  parameters:
    PageParam:
      name: page
      in: query
      schema: { type: integer, minimum: 1, default: 1 }
    PerPageParam:
      name: per_page
      in: query
      schema: { type: integer, minimum: 1, maximum: 100, default: 20 }

  responses:
    Unauthorized:
      description: Missing or invalid authentication
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ValidationError:
      description: Request validation failed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

security:
  - BearerAuth: []

Spec Quality Checklist (score each 0-2)

#CheckScore
1Every endpoint has operationId/2
2All parameters documented with types + constraints/2
3Request bodies have examples/2
4All error responses documented (400, 401, 403, 404, 422, 429, 500)/2
5Shared schemas use $ref (DRY)/2
6Pagination parameters standardized/2
7Security scheme defined + applied globally/2
8Description includes auth, rate limits, versioning info/2
9Response headers documented (Location, Retry-After, ETag)/2
10Enums used for fixed value sets/2

Score: ___/20 (Target: 16+)


Phase 3: Implementation Patterns

Request Validation Layer

Every endpoint MUST validate before processing:

Validation Order:
1. Content-Type header (reject non-JSON early)
2. Authentication (401 before wasting cycles)
3. Authorization (403 - does this user have access?)
4. Path parameters (404 - does the resource exist?)
5. Query parameters (400 - valid types/ranges?)
6. Request body schema (422 - valid structure?)
7. Business rules (422 - valid state transition?)

Error Handling — Standard Error Codes

Define a consistent error code enum for your API:

# Authentication & Authorization
AUTH_REQUIRED          — No credentials provided
AUTH_INVALID           — Invalid/expired credentials
AUTH_INSUFFICIENT      — Valid credentials, wrong permissions
AUTH_RATE_LIMITED       — Too many auth attempts

# Validation
VALIDATION_FAILED      — Generic validation error (see details array)
INVALID_FORMAT         — Field format wrong (email, UUID, etc.)
REQUIRED_FIELD         — Required field missing
OUT_OF_RANGE           — Value outside allowed range
INVALID_ENUM           — Value not in allowed set

# Resource
NOT_FOUND              — Resource doesn't exist
ALREADY_EXISTS         — Duplicate (unique constraint)
CONFLICT               — State conflict (e.g., already cancelled)
GONE                   — Resource permanently deleted

# Business Logic
INSUFFICIENT_FUNDS     — Payment-related
QUOTA_EXCEEDED         — Usage limit reached
FEATURE_DISABLED       — Feature flag off
DEPENDENCY_FAILED      — Upstream service error

# System
INTERNAL_ERROR         — Unexpected server error
SERVICE_UNAVAILABLE    — Temporarily down
TIMEOUT                — Request took too long

Idempotency

For non-idempotent operations (POST), require an idempotency key:

Request:
POST /orders
Idempotency-Key: ord_req_abc123

Server behavior:
1. Check if Idempotency-Key was seen before
2. If yes → return cached response (same status, same body)
3. If no → process request, cache response for 24h
4. Key format: client-generated UUID or meaningful string

Rate Limiting

Standard headers to include:

X-RateLimit-Limit: 100          # Max requests per window
X-RateLimit-Remaining: 67       # Remaining in current window
X-RateLimit-Reset: 1706886400   # Unix timestamp when window resets
Retry-After: 30                 # Seconds to wait (on 429)

Rate limit tiers:

TierLimitWindowUse Case
Standard100/minSlidingNormal API calls
Bulk10/minSlidingBatch operations
Search30/minSlidingFull-text search
Auth5/minFixedLogin attempts
Webhook1000/minSlidingIncoming webhooks

Phase 4: Testing Strategy

Test Pyramid for APIs

        /  E2E  \          — 5-10 critical user flows
       / Contract \        — Schema validation, backward compat
      / Integration \      — Database, external services, auth
     /    Unit Tests  \    — Business logic, validation, transforms
    ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

Test Checklist Per Endpoint

For EVERY endpoint, test these scenarios:

endpoint: POST /orders
tests:
  happy_path:
    - Creates order with valid data → 201
    - Returns created resource with ID
    - Location header points to new resource
    - Timestamps are set (created_at, updated_at)
  
  validation:
    - Missing required fields → 422 with field-level errors
    - Invalid field types (string where int expected) → 422
    - Empty body → 400
    - Invalid Content-Type → 415
    - Extra unknown fields → ignored or 422 (pick one, be consistent)
    - Boundary values (min/max length, 0, negative, empty string vs null)
  
  authentication:
    - No token → 401
    - Expired token → 401
    - Invalid token → 401
    - Valid token, wrong scope → 403
  
  authorization:
    - User accessing own resource → 200
    - User accessing other's resource → 403 or 404 (security choice)
    - Admin accessing any resource → 200
  
  edge_cases:
    - Duplicate creation (same idempotency key) → same 201 response
    - Concurrent creation race condition → one wins, one gets 409
    - Resource at max relationships → 422
    - Unicode in text fields → handled correctly
    - Very long strings → 422 with max length error
    - SQL injection in params → no effect (parameterized queries)
    - XSS in text fields → stored safely, escaped on output
  
  performance:
    - Response time < 200ms (p95)
    - List endpoint with 10K records → paginated, < 500ms
    - Bulk operation timeout handling

curl Testing Recipes

# === Setup ===
BASE="https://api.example.com/v1"
TOKEN="your_bearer_token"
alias api='curl -s -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json"'

# === CRUD Lifecycle Test ===
# Create
ORDER=$(api -X POST "$BASE/orders" -d '{"customer_id":"cust_1","items":[{"product_id":"prod_1","qty":2}]}')
ORDER_ID=$(echo "$ORDER" | jq -r '.data.id')
echo "Created: $ORDER_ID"

# Read
api "$BASE/orders/$ORDER_ID" | jq .

# Update
api -X PATCH "$BASE/orders/$ORDER_ID" -d '{"notes":"Rush order"}' | jq .

# List with filters
api "$BASE/orders?status=draft&sort=-created_at&per_page=5" | jq .

# Action (state transition)
api -X POST "$BASE/orders/$ORDER_ID/confirm" | jq .

# Delete
curl -s -o /dev/null -w "%{http_code}" -X DELETE -H "Authorization: Bearer $TOKEN" "$BASE/orders/$ORDER_ID"

# === Error Testing ===
# No auth
curl -s "$BASE/orders" | jq .error

# Invalid body
api -X POST "$BASE/orders" -d '{"invalid": true}' | jq .error

# Not found
api "$BASE/orders/nonexistent" | jq .error

# === Performance ===
# Timing breakdown
curl -s -o /dev/null -w "DNS:%{time_namelookup} TCP:%{time_connect} TLS:%{time_appconnect} TTFB:%{time_starttransfer} Total:%{time_total}\
" -H "Authorization: Bearer $TOKEN" "$BASE/orders"

# Quick load test (50 requests, 10 concurrent)
seq 50 | xargs -P10 -I{} curl -s -o /dev/null -w "%{http_code} %{time_total}s\
" -H "Authorization: Bearer $TOKEN" "$BASE/orders"

Contract Testing

Validate your API hasn't broken backward compatibility:

# contract-tests.yaml
contract:
  name: Order API Contract
  version: 1.0.0
  
  rules:
    # These changes are SAFE (non-breaking)
    safe:
      - Adding new optional fields to responses
      - Adding new endpoints
      - Adding new optional query parameters
      - Adding new enum values (if clients handle unknown)
      - Widening a constraint (min: 5 → min: 1)
    
    # These changes are BREAKING
    breaking:
      - Removing a response field
      - Renaming a response field
      - Changing a field type
      - Adding a new required request field
      - Removing an endpoint
      - Narrowing a constraint (max: 100 → max: 50)
      - Changing error response format
      - Removing an enum value
    
    # Verify after every change
    checks:
      - All existing fields still present in responses
      - All existing field types unchanged
      - All existing required fields still required (no more, no fewer)
      - Default values unchanged
      - Error format unchanged

Phase 5: Security

Security Checklist (audit every API)

authentication:
  - [ ] All endpoints require auth (except /health, /docs, public webhooks)
  - [ ] Tokens expire (short-lived access + long-lived refresh)
  - [ ] Token rotation supported
  - [ ] Failed auth returns 401 with no info leakage
  - [ ] API keys are hashed in storage (never plain text)

authorization:
  - [ ] Resource-level checks (user can only access their data)
  - [ ] Endpoint-level checks (role-based access)
  - [ ] No IDOR vulnerabilities (can't guess other users' resource IDs)
  - [ ] Admin endpoints separately protected
  - [ ] Webhook endpoints verify signatures

input_validation:
  - [ ] All inputs validated server-side (never trust client)
  - [ ] SQL injection prevented (parameterized queries only)
  - [ ] NoSQL injection prevented
  - [ ] Path traversal prevented
  - [ ] Request size limited (body, headers, URL length)
  - [ ] File upload types restricted and scanned

output_security:
  - [ ] No sensitive data in responses (passwords, tokens, internal IDs)
  - [ ] No stack traces in production errors
  - [ ] Consistent error format (no info leakage in different error types)
  - [ ] PII redacted in logs

transport:
  - [ ] HTTPS only (HTTP redirects to HTTPS)
  - [ ] HSTS header set
  - [ ] TLS 1.2+ required
  - [ ] CORS configured restrictively (specific origins, not *)
  
headers:
  - [ ] X-Content-Type-Options: nosniff
  - [ ] X-Frame-Options: DENY
  - [ ] Content-Security-Policy set
  - [ ] No Server version header
  - [ ] Cache-Control: no-store for sensitive endpoints

CORS Configuration

# Restrictive (recommended)
cors:
  origins:
    - https://app.example.com
    - https://admin.example.com
  methods: [GET, POST, PUT, PATCH, DELETE]
  headers: [Authorization, Content-Type, X-Request-ID]
  credentials: true
  max_age: 3600

# Common mistakes to avoid:
# ❌ Access-Control-Allow-Origin: *  (with credentials)
# ❌ Reflecting Origin header without validation
# ❌ Allowing all methods/headers

Phase 6: Versioning & Deprecation

Versioning Strategy Decision

StrategyExampleProsConsUse When
URL path/v1/ordersExplicit, easy routingURL pollutionPublic APIs, multiple major versions
HeaderAPI-Version: 2024-01Clean URLsHidden, harder to testInternal APIs
Query param?version=2Easy to testPollutes paramsQuick prototypes
Date-based2024-01-15Clear timelineMany versionsStripe-style APIs

Recommended: URL path for major versions, header for minor variations.

Deprecation Playbook

Timeline:
1. T+0: Announce deprecation (docs, changelog, email)
2. T+0: Add Deprecation + Sunset headers to old endpoints
3. T+30d: Log warnings for old endpoint usage
4. T+60d: Email heavy users of old endpoint directly
5. T+90d: Return 299 warning header
6. T+180d: Shut down old endpoint (410 Gone)

Headers:
Deprecation: true
Sunset: Sat, 01 Jun 2025 00:00:00 GMT
Link: <https://api.example.com/v2/orders>; rel="successor-version"

Migration Guide Template

# Migrating from v1 to v2

## Breaking Changes
1. `user.name` split into `user.first_name` + `user.last_name`
2. Pagination changed from offset to cursor-based
3. Error format updated (see new schema)

## Step-by-Step Migration
1. Update your client SDK to v2 (`npm install @example/sdk@2`)
2. Update response parsing for split name fields
3. Replace `?page=N` with `?after=cursor` pagination
4. Update error handling for new error format

## Compatibility Mode
Set `X-Compat-Mode: v1` header to get v1-style responses from v2 endpoints.
Available until 2025-06-01.

Phase 7: Monitoring & Observability

Key Metrics Dashboard

availability:
  - Uptime percentage (target: 99.9% = 8.7h downtime/year)
  - Health check status (/health endpoint)
  - Error rate (5xx / total requests)

performance:
  - p50 latency (target: < 100ms)
  - p95 latency (target: < 500ms)
  - p99 latency (target: < 1000ms)
  - Throughput (requests/second)
  - Time to first byte (TTFB)

business:
  - Requests per endpoint (usage patterns)
  - Unique API consumers/day
  - Error rate by endpoint
  - Rate limit hits/day
  - Authentication failures/day

infrastructure:
  - Database query time (p95)
  - Connection pool utilization
  - Memory/CPU per instance
  - Queue depth (async operations)

Structured Logging

Every request should log:

{
  "timestamp": "2024-01-15T10:30:00.000Z",
  "level": "info",
  "request_id": "req_abc123",
  "method": "POST",
  "path": "/api/v1/orders",
  "status": 201,
  "duration_ms": 45,
  "user_id": "usr_xyz",
  "ip": "203.0.113.1",
  "user_agent": "MyApp/2.0",
  "request_size": 256,
  "response_size": 1024
}

Health Check Endpoint

// GET /health — for load balancers (simple)
{ "status": "ok" }

// GET /health/detailed — for monitoring (authenticated)
{
  "status": "degraded",
  "version": "1.5.2",
  "uptime_seconds": 86400,
  "checks": {
    "database": { "status": "ok", "latency_ms": 5 },
    "redis": { "status": "ok", "latency_ms": 2 },
    "external_payment_api": { "status": "degraded", "latency_ms": 2500, "error": "timeout" },
    "disk": { "status": "ok", "free_gb": 45.2 }
  }
}

Phase 8: API Review Scoring

When reviewing an existing API, score across these dimensions:

API Quality Rubric (0-100)

DimensionWeightCriteriaScore
Design Consistency20%Naming conventions, HTTP methods, status codes, URL structure/20
Documentation15%OpenAPI spec, examples, error docs, changelog/15
Error Handling15%Consistent format, helpful messages, proper codes, no leakage/15
Security20%Auth, input validation, CORS, headers, no IDOR/20
Performance15%Latency targets met, pagination, caching headers, N+1 prevented/15
Developer Experience15%SDK quality, sandbox available, onboarding time, rate limit clarity/15

Score: ___/100

RatingScoreAction
🟢 Excellent85-100Minor improvements only
🟡 Good70-84Address gaps before next major release
🟠 Needs Work50-69Prioritize improvements, create tech debt tickets
🔴 Critical<50Stop feature work, fix fundamentals first

Review Output Template

## API Review: [Service Name]

**Date:** YYYY-MM-DD
**Reviewer:** [Agent]
**Score:** XX/100 (Rating)

### Summary
[2-3 sentence overview of API quality]

### Scores by Dimension
- Design Consistency: X/20 — [key finding]
- Documentation: X/15 — [key finding]
- Error Handling: X/15 — [key finding]
- Security: X/20 — [key finding]
- Performance: X/15 — [key finding]
- Developer Experience: X/15 — [key finding]

### Critical Issues (fix immediately)
1. [Issue + recommendation]

### High Priority (fix this sprint)
1. [Issue + recommendation]

### Nice to Have (backlog)
1. [Issue + recommendation]

### Positive Highlights
- [What's working well]

GraphQL-Specific Guidance

Schema Design Principles

# Good: clear types, nullable where appropriate, connections for lists
type Order {
  id: ID!
  status: OrderStatus!
  customer: Customer!
  items(first: Int, after: String): ItemConnection!
  total: Money!
  createdAt: DateTime!
  updatedAt: DateTime!
}

type Money {
  amount: Int!       # cents, not dollars (avoid float)
  currency: Currency!
}

enum OrderStatus {
  DRAFT
  CONFIRMED
  PROCESSING
  SHIPPED
  DELIVERED
  CANCELLED
}

# Mutations return the modified resource + errors
type CreateOrderPayload {
  order: Order
  errors: [UserError!]!
}

type UserError {
  field: [String!]
  message: String!
  code: ErrorCode!
}

GraphQL Anti-Patterns

Anti-PatternProblemFix
No depth limitQuery bombsLimit depth to 5-7 levels
No complexity limitExpensive queriesAssign cost per field, cap at 1000
N+1 queriesPerformance deathUse DataLoader pattern
No persisted queriesSecurity riskWhitelist queries in production
Exposing internal IDsLeaks implementationUse opaque global IDs
No paginationMemory explosionUse Relay Connection spec

Edge Cases & Gotchas

Timezone Handling

  • Always store and return UTC (ISO 8601: 2024-01-15T10:30:00Z)
  • Accept timezone in input, convert to UTC immediately
  • Never use local server time

Large Payloads

  • Set Content-Length limits (e.g., 1MB default, 10MB for uploads)
  • Use streaming for file uploads (multipart/form-data)
  • Compress responses (Accept-Encoding: gzip)
  • For very large exports → return 202 + poll status endpoint

Eventual Consistency

  • If using async processing, always return 202 + status URL
  • Include estimated completion time when possible
  • Client should poll with exponential backoff

Concurrent Updates

  • Use ETags for optimistic concurrency:

- GET returns ETag: "v1" header - PUT/PATCH sends If-Match: "v1" header - Server returns 412 if resource changed since

Webhook Design

  • Include event type, timestamp, and full resource in payload
  • Sign payloads (HMAC-SHA256)
  • Expect retries (make handlers idempotent)
  • Return 200 quickly, process async
  • Include webhook ID for deduplication

Quick Commands

RequestAction
"Design an API for [domain]"Run Phase 1 resource modeling + naming
"Generate OpenAPI spec"Run Phase 2 with full components
"Review this API"Run Phase 8 scoring rubric
"Write tests for [endpoint]"Run Phase 4 endpoint checklist
"Security audit this API"Run Phase 5 security checklist
"How should I version this?"Run Phase 6 decision matrix
"Debug this API issue"Check Phase 7 logging + health patterns
"Design GraphQL schema for [domain]"Run GraphQL section

平台分布

OpenClaw

87.43%
按下载量换算6,556

安全审计

VirusTotal

可疑

ClawScan

通过

Static analysis

未展示

权限和风险

接触敏感数据

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

安装前确认

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

继续浏览同类 Skills