Token导航 LogoToken导航TokenDH.com
前端设计操作浏览器github未标认证来源可访问clear审计提醒

implementing-api-patternsimplementing API 模式

Agent Skill

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

总安装

808

周安装

33

GitHub Stars

350

下载量

259
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/ancoleman/ai-design-components --skill implementing-api-patterns

简介

implementing-api-patterns 用于辅助 API 设计、接口文档和错误码整理,支持服务集成说明。

  • 适用于梳理 endpoint、生成 OpenAPI 草稿或检查字段命名规范等场景。
  • 可辅助前后端联调,但需避免凭空补字段,应基于现有代码或样例提取事实。
  • 安装命令为 npx skills add https://github.com/ancoleman/ai-design-components --skill implementing-api-patterns。
  • 使用时需确认业务语义、鉴权方式和分页规则,确保接口定义准确。

SKILL.md

API Patterns Skill

Purpose

Design and implement APIs using the optimal pattern and framework for the use case. Choose between REST, GraphQL, gRPC, and tRPC based on API consumers, performance requirements, and type safety needs.

When to Use This Skill

Use when:

  • Building backend APIs for web, mobile, or service consumers
  • Connecting frontend components (forms, tables, dashboards) to databases
  • Implementing pagination, rate limiting, or caching strategies
  • Generating OpenAPI documentation automatically
  • Choosing between REST, GraphQL, gRPC, or tRPC patterns
  • Integrating authentication and authorization
  • Optimizing API performance and scalability

Quick Decision Framework

WHO CONSUMES YOUR API?
├─ PUBLIC/THIRD-PARTY DEVELOPERS → REST with OpenAPI
│  ├─ Python → FastAPI (auto-docs, 40k req/s)
│  ├─ TypeScript → Hono (edge-first, 50k req/s, 14KB)
│  ├─ Rust → Axum (140k req/s, <1ms latency)
│  └─ Go → Gin (100k+ req/s, mature ecosystem)
│
├─ FRONTEND TEAM (same org)
│  ├─ TypeScript full-stack? → tRPC (E2E type safety)
│  └─ Complex data needs? → GraphQL
│      ├─ Python → Strawberry
│      ├─ Rust → async-graphql
│      ├─ Go → gqlgen
│      └─ TypeScript → Pothos
│
├─ SERVICE-TO-SERVICE (microservices)
│  └─ High performance → gRPC
│      ├─ Rust → Tonic
│      ├─ Go → Connect-Go (browser-friendly)
│      └─ Python → grpcio
│
└─ MOBILE APPS
   ├─ Bandwidth constrained → GraphQL (request only needed fields)
   └─ Simple CRUD → REST (standard, well-understood)

REST Framework Selection

Python: FastAPI (Recommended)

Key Features: Auto OpenAPI docs, Pydantic v2 validation, async/await, 40k req/s

Basic Example:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
async def create_item(item: Item):
    return {"id": 1, **item.dict()}

See references/rest-design-principles.md for FastAPI patterns and examples/python-fastapi/.

TypeScript: Hono (Edge-First)

Key Features: 14KB bundle, runs on any runtime (Node/Deno/Bun/edge), Zod validation, 50k req/s

Basic Example:

import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'

const app = new Hono()
app.post('/items', zValidator('json', z.object({
  name: z.string(), price: z.number()
})), (c) => c.json({ id: 1, ...c.req.valid('json') }))

See references/rest-design-principles.md for Hono patterns and examples/typescript-hono/.

TypeScript: tRPC (Full-Stack Type Safety)

Key Features: Zero codegen, E2E type safety, React Query integration, WebSocket subscriptions

Basic Example:

import { initTRPC } from '@trpc/server'
import { z } from 'zod'

const t = initTRPC.create()
export const appRouter = t.router({
  createItem: t.procedure
    .input(z.object({ name: z.string(), price: z.number() }))
    .mutation(({ input }) => ({ id: '1', ...input }))
})
export type AppRouter = typeof appRouter

See references/trpc-setup-guide.md for setup patterns and examples/typescript-trpc/.

Rust: Axum (High Performance)

Key Features: Tower middleware, type-safe extractors, 140k req/s, compile-time verification

Basic Example:

use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct CreateItem { name: String, price: f64 }

#[derive(Serialize)]
struct Item { id: u64, name: String, price: f64 }

async fn create_item(Json(payload): Json<CreateItem>) -> Json<Item> {
    Json(Item { id: 1, name: payload.name, price: payload.price })
}

See references/rest-design-principles.md for Axum patterns and examples/rust-axum/.

Go: Gin (Mature Ecosystem)

Key Features: Largest Go ecosystem, 100k+ req/s, struct tag validation

Basic Example:

type Item struct {
    Name  string  `json:"name" binding:"required"`
    Price float64 `json:"price" binding:"required,gt=0"`
}

r := gin.Default()
r.POST("/items", func(c *gin.Context) {
    var item Item
    if c.ShouldBindJSON(&item); err != nil {
        c.JSON(400, gin.H{"error": err.Error()}); return
    }
    c.JSON(201, item)
})

See references/rest-design-principles.md for Gin patterns and examples/go-gin/.

Performance Benchmarks

LanguageFrameworkReq/sLatencyCold StartMemoryBest For
RustActix-web~150k<1msN/A2-5MBMaximum throughput
RustAxum~140k<1msN/A2-5MBErgonomics + performance
GoGin~100k+1-2msN/A5-10MBMature ecosystem
TypeScriptHono~50k<5ms<5ms128MBEdge deployment
PythonFastAPI~40k5-10ms1-2s30-50MBDeveloper experience
TypeScriptExpress~15k10-20ms1-3s50-100MBLegacy systems

Notes:

  • Benchmarks assume single-core, JSON responses
  • Actual performance varies with workload complexity
  • Cold start only applies to serverless/edge deployments

Pagination Strategies

Cursor-Based (Recommended)

Advantages: Handles real-time changes, no skipped/duplicate records, scales to billions

FastAPI Example:

@app.get("/items")
async def list_items(cursor: Optional[str] = None, limit: int = 20):
    query = db.query(Item).filter(Item.id > cursor) if cursor else db.query(Item)
    items = query.limit(limit).all()
    return {
        "items": items,
        "next_cursor": items[-1].id if items else None,
        "has_more": len(items) == limit
    }

Offset-Based (Simple Cases Only)

Use only for static datasets (<10k records) with direct page access needs.

See references/pagination-patterns.md for complete patterns and frontend integration.

OpenAPI Documentation

FrameworkOpenAPI SupportDocs UIConfiguration
FastAPIAutomaticSwagger UI + ReDocBuilt-in
HonoMiddleware pluginSwagger UI@hono/swagger-ui
Axumutoipa crateSwagger UIManual annotations
Ginswaggo/swagSwagger UIComment annotations

FastAPI Example (Zero Config):

app = FastAPI(title="My API", version="1.0.0")

@app.post("/items", tags=["items"])
async def create_item(item: Item) -> Item:
    """Create item with name and price"""
    return item
# Docs at /docs, /redoc, /openapi.json

See references/openapi-documentation.md for framework-specific setup. Use scripts/generate_openapi.py to extract specs programmatically.

Frontend Integration Patterns

Forms → REST POST/PUT

Backend:

class UserCreate(BaseModel):
    email: EmailStr; name: str; age: int

@app.post("/api/users", status_code=201)
async def create_user(user: UserCreate):
    return {"id": 1, **user.dict()}

Frontend:

const res = await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(data)
})
if (!res.ok) throw new Error((await res.json()).detail)

Tables → GET with Pagination

See cursor pagination example above and references/pagination-patterns.md.

AI Chat → SSE Streaming

Backend:

from sse_starlette.sse import EventSourceResponse

@app.post("/api/chat")
async def chat(message: str):
    async def gen():
        for chunk in llm_stream(message):
            yield {"event": "message", "data": chunk}
    return EventSourceResponse(gen())

Frontend:

const es = new EventSource('/api/chat')
es.addEventListener('message', (e) => appendToChat(e.data))

See examples/ for complete integration examples with each frontend skill.

Rate Limiting

FastAPI Example (Token Bucket):

from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter

@app.get("/items")
@limiter.limit("100/minute")
async def list_items():
    return {"items": []}

See references/rate-limiting-strategies.md for sliding window, distributed patterns, and Redis implementation.

GraphQL Libraries

Use when frontend needs flexible data fetching or mobile apps have bandwidth constraints.

By Language:

  • Python: Strawberry 0.287 (type-hint-based, async)
  • Rust: async-graphql (high performance, tokio)
  • Go: gqlgen (code generation from schema)
  • TypeScript: Pothos (type-safe builder, no codegen)

See references/graphql-schema-design.md for schema patterns and N+1 prevention. See examples/graphql-strawberry/ for complete Python example.

gRPC for Microservices

Use for service-to-service communication with strong typing and high performance.

By Language:

  • Rust: Tonic (async, type-safe, code generation)
  • Go: Connect-Go (gRPC-compatible + browser-friendly)
  • Python: grpcio (official implementation)
  • TypeScript: @connectrpc/connect (browser + Node.js)

See references/grpc-protobuf-guide.md for Protocol Buffers guide. See examples/grpc-tonic/ for complete Rust example.

Additional Resources

References

  • references/rest-design-principles.md - REST resource modeling, HTTP methods, status codes
  • references/graphql-schema-design.md - Schema patterns, resolver optimization, N+1 prevention
  • references/grpc-protobuf-guide.md - Proto3 syntax, service definitions, streaming
  • references/trpc-setup-guide.md - Router patterns, middleware, Zod validation
  • references/pagination-patterns.md - Cursor vs offset with mathematical explanation
  • references/rate-limiting-strategies.md - Token bucket, sliding window, Redis
  • references/caching-patterns.md - HTTP caching, application caching strategies
  • references/versioning-strategies.md - URI, header, media type versioning
  • references/openapi-documentation.md - Swagger/OpenAPI best practices by framework

Scripts (Token-Free Execution)

  • scripts/generate_openapi.py - Generate OpenAPI spec from code
  • scripts/validate_api_spec.py - Validate OpenAPI 3.1 compliance
  • scripts/benchmark_endpoints.py - Load test API endpoints

Examples

  • examples/python-fastapi/ - Complete FastAPI REST API
  • examples/typescript-hono/ - Hono edge-first API
  • examples/typescript-trpc/ - tRPC E2E type-safe API
  • examples/rust-axum/ - Axum REST API
  • examples/go-gin/ - Gin REST API
  • examples/graphql-strawberry/ - Python GraphQL
  • examples/grpc-tonic/ - Rust gRPC

Quick Reference

Choose REST when: Public API, standard CRUD, need caching, OpenAPI docs required Choose GraphQL when: Frontend needs flexible queries, mobile bandwidth constraints, complex nested data Choose gRPC when: Service-to-service communication, high performance, bidirectional streaming Choose tRPC when: TypeScript full-stack, same team owns frontend + backend, E2E type safety

Pagination: Always use cursor-based for production scale, offset-based only for simple cases Documentation: Prefer frameworks with automatic OpenAPI generation (FastAPI, Hono) Performance: Rust (Axum) for max throughput, Go (Gin) for maturity, Python (FastAPI) for DX

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenCode

29.57%
按下载量换算77

Gemini CLI

24.03%
按下载量换算62

Antigravity

15.47%
按下载量换算40

Claude Code

12.35%
按下载量换算32

roo

7.42%
按下载量换算19

Cursor

3.77%
按下载量换算10

安全审计

Gen Agent Trust Hub

可疑

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills