本文へ移動
cccskills
無料GitHub で公開

api-design-ops

API design patterns for REST, gRPC, and GraphQL. Use for: api design, REST, gRPC, GraphQL, protobuf, schema design, api versioning, pagination, rate limiting, error format, OpenAPI, API authentication, JWT, OAuth2, API gateway, webhook, idempotency.

インストール方法を見る

含まれるファイル(7)

  • SKILL.md10.9 KB
  • assets/.gitkeep0 B
  • references/api-security.md18.8 KB
  • references/graphql.md19.6 KB
  • references/grpc.md18.2 KB
  • references/rest-advanced.md13.6 KB
  • scripts/.gitkeep0 B

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

API Design Ops

Comprehensive API design patterns covering REST (advanced), gRPC, and GraphQL. This skill provides decision frameworks, design patterns, and implementation guidance for building production APIs.

API Style Decision Tree

What kind of API do you need?
|
+-- Internal microservice-to-microservice?
|   +-- High throughput, low latency needed? --> gRPC
|   +-- Streaming (real-time data, logs)? --> gRPC (bidirectional streaming)
|   +-- Simple request/response, team comfort? --> REST
|
+-- Public-facing API?
|   +-- Third-party developers consuming it? --> REST (widest compatibility)
|   +-- Mobile app with varied data needs? --> GraphQL
|   +-- Browser-only, simple CRUD? --> REST
|
+-- Frontend for your own app?
|   +-- Multiple clients with different data shapes? --> GraphQL
|   +-- Single client, straightforward data? --> REST
|   +-- Real-time updates needed? --> GraphQL subscriptions or SSE
|
+-- IoT / embedded / constrained devices?
|   +-- Binary efficiency matters? --> gRPC
|   +-- HTTP-only environments? --> REST

Quick Comparison

ConcernRESTgRPCGraphQL
TransportHTTP/1.1+HTTP/2HTTP (any)
SerializationJSON (text)Protobuf (binary)JSON (text)
SchemaOpenAPI (optional).proto (required)SDL (required)
Browser supportNativeVia gRPC-Web/ConnectNative
CachingHTTP caching built-inCustomCustom (normalized)
Learning curveLowMediumMedium-High
Code generationOptionalRequiredOptional but recommended
StreamingSSE, WebSocketNative (4 patterns)Subscriptions
Over-fetchingCommon problemNo (typed)Solved by design
File uploadsMultipart nativeChunked streamingMultipart spec (awkward)

REST Resource Design Quick Reference

Resource Naming

GET    /users                  # Collection
GET    /users/{id}             # Singleton
GET    /users/{id}/orders      # Sub-collection
POST   /users                  # Create
PUT    /users/{id}             # Full replace
PATCH  /users/{id}             # Partial update
DELETE /users/{id}             # Remove

# Naming rules:
# - Plural nouns for collections: /users NOT /user
# - Kebab-case for multi-word: /line-items NOT /lineItems
# - No verbs in URLs: POST /orders NOT POST /create-order
# - Max 3 levels deep: /users/{id}/orders (not /users/{id}/orders/{oid}/items/{iid}/details)

HTTP Methods and Status Codes

MethodSuccessEmptyInvalidNot FoundConflict
GET200200 (empty array)400404-
POST201 + Location-400/422-409
PUT200-400/422404409
PATCH200-400/422404409
DELETE204204 (already gone)400404409

HATEOAS (When Worth It)

Use when: public APIs where discoverability matters, long-lived APIs, APIs that evolve frequently. Skip when: internal microservices, mobile backends, tight coupling is acceptable.

{
  "id": "order-123",
  "status": "shipped",
  "_links": {
    "self": { "href": "/orders/order-123" },
    "track": { "href": "/orders/order-123/tracking" },
    "cancel": { "href": "/orders/order-123", "method": "DELETE" }
  }
}

Pagination Decision Tree

What's your data like?
|
+-- Stable data, UI needs "jump to page 5"?
|   --> Offset pagination: ?page=5&per_page=20
|   Tradeoff: Slow on large offsets (OFFSET 10000), inconsistent with inserts
|
+-- Large dataset, forward-only traversal?
|   --> Cursor pagination: ?after=eyJpZCI6MTIzfQ&limit=20
|   Tradeoff: No random page access, but consistent and fast
|
+-- Real-time feed, ordered by timestamp or ID?
|   --> Keyset pagination: ?created_after=2024-01-01T00:00:00Z&limit=20
|   Tradeoff: Requires a unique, sequential column; no page jumping

Response Envelope

{
  "data": [...],
  "pagination": {
    "total": 1432,
    "limit": 20,
    "has_more": true,
    "next_cursor": "eyJpZCI6MTQzMn0="
  }
}

Error Response Format (RFC 7807)

All APIs should use Problem Details (RFC 7807 / RFC 9457):

{
  "type": "https://api.example.com/errors/insufficient-funds",
  "title": "Insufficient Funds",
  "status": 422,
  "detail": "Account xxxx-1234 has a balance of $10.00, but the transfer requires $25.00.",
  "instance": "/transfers/txn-abc-123",
  "balance": 1000,
  "required": 2500
}

Field Reference

FieldRequiredDescription
typeYesURI identifying the error type (stable, documentable)
titleYesHuman-readable summary (same for all instances of this type)
statusYesHTTP status code
detailYesHuman-readable explanation specific to this occurrence
instanceNoURI identifying the specific occurrence
(extensions)NoAdditional machine-readable fields

Validation Errors

{
  "type": "https://api.example.com/errors/validation",
  "title": "Validation Failed",
  "status": 422,
  "detail": "The request body contains 2 validation errors.",
  "errors": [
    { "field": "email", "message": "Must be a valid email address", "code": "invalid_format" },
    { "field": "age", "message": "Must be at least 18", "code": "out_of_range", "min": 18 }
  ]
}

Versioning Strategies

StrategyExampleProsCons
URL path/v2/usersObvious, cacheable, easy routingURL pollution, hard to sunset
Accept headerAccept: application/vnd.api.v2+jsonClean URLs, content negotiationHidden, harder to test
Query param/users?version=2Easy to addPollutes query string, caching issues
Date-basedAPI-Version: 2024-01-15Granular evolution (Stripe style)Complex implementation

Recommendation

  • Public APIs: URL path versioning (/v1/) - simplicity wins
  • Internal APIs: Header or no versioning (deploy in lockstep)
  • Evolving APIs: Date-based (Stripe model) if you have the engineering investment

Breaking Change Rules

A breaking change is anything that can cause existing clients to fail:

  • Removing a field from a response
  • Renaming a field
  • Changing a field's type
  • Adding a required field to a request
  • Changing URL structure
  • Changing error formats
  • Removing an endpoint

Non-breaking (safe):

  • Adding optional fields to requests
  • Adding fields to responses
  • Adding new endpoints
  • Adding new enum values (if client handles unknown values)

Rate Limiting Design

Algorithms

AlgorithmBehaviorUse When
Token bucketAllows bursts, refills at steady rateGeneral API rate limiting
Sliding windowSmooth distribution, no burstStrict fairness needed
Fixed windowSimple, potential burst at boundaryLow-stakes limiting
Leaky bucketConstant output rateQueue processing

Response Headers

X-RateLimit-Limit: 1000          # Max requests per window
X-RateLimit-Remaining: 743       # Requests left in current window
X-RateLimit-Reset: 1672531200    # Unix timestamp when window resets
Retry-After: 30                  # Seconds to wait (on 429)

429 Response Body

{
  "type": "https://api.example.com/errors/rate-limit-exceeded",
  "title": "Rate Limit Exceeded",
  "status": 429,
  "detail": "You have exceeded 1000 requests per hour. Try again in 30 seconds.",
  "retry_after": 30
}

Idempotency

Which Methods Need Idempotency Keys?

MethodIdempotent by spec?Needs key?
GETYesNo
PUTYesNo (full replacement is naturally idempotent)
DELETEYesNo
PATCHNoRecommended for critical operations
POSTNoYes (always for payments, orders, transfers)

Implementation

POST /payments
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
Content-Type: application/json

{ "amount": 2500, "currency": "usd", "customer": "cust_123" }

Server-side:

  1. Receive request with Idempotency-Key header
  2. Check if key exists in store (Redis, DB)
  3. If exists: return stored response (same status code + body)
  4. If not: process request, store response keyed by idempotency key
  5. Keys expire after 24-48 hours

Authentication Overview

MethodUse WhenSecurity Level
API KeyServer-to-server, internal, simpleLow-Medium
JWT (Bearer)Stateless auth, microservicesMedium-High
OAuth2 + PKCEThird-party access, user delegationHigh
mTLSService mesh, zero-trust infraVery High

Decision Guide

Who is authenticating?
|
+-- Your own frontend? --> JWT (short-lived access + refresh token)
+-- Third-party developer? --> OAuth2 (client credentials for server, PKCE for SPA)
+-- Another internal service? --> mTLS or JWT with service accounts
+-- Quick prototype? --> API key (but plan migration)

Gotchas Table

GotchaProblemPrevention
Breaking changes in "non-breaking" releaseClient crashesAdditive-only policy, contract tests
N+1 in REST APIs100 users = 101 queriesCompound documents, ?include=, or GraphQL
Over-fetchingMobile gets 50 fields, needs 3Sparse fieldsets ?fields=id,name or GraphQL
Under-fetching3 requests to build one viewComposite endpoints or BFF pattern
CORS misconfigurationFrontend can't reach APIExplicit allowed origins, never * with credentials
Missing Content-Type415 or silent parsing failureValidate Content-Type on every mutation endpoint
Large payloads without paginationOOM, timeoutsAlways paginate collections, set max page size
Inconsistent date formatsParsing hellISO 8601 everywhere: 2024-01-15T10:30:00Z
No request IDsImpossible to debugGenerate X-Request-ID, propagate through services
Enum evolutionNew value breaks old clientDocument that enums may grow, clients must handle unknown
Missing idempotencyDuplicate charges, ordersIdempotency keys on all POST endpoints with side effects
Unbounded query complexityGraphQL DoSDepth limiting, cost analysis, persisted queries

Reference Files

FileContents
references/rest-advanced.mdResource modeling, PATCH strategies, caching, webhooks, bulk ops
references/grpc.mdProtobuf, service definitions, Go/Rust, streaming, error handling
references/graphql.mdSchema design, resolvers, DataLoader, federation, performance
references/api-security.mdJWT, OAuth2, CORS, rate limiting, OWASP API Top 10

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Primary accessibility skill for VS Code. REQUIRED for new feature and contribution work, and also applies to updates of existing UI. Covers accessibility help dialogs, accessible views, verbosity settings, signals, ARIA announcements, keyboard navigation, and ARIA labels/roles.

日本語の概要は準備中です。原文の説明を表示しています。

jcasnellie69/homelab-config22026年10月12日 更新

Use this skill when the user explicitly asks to map, document, or onboard into an existing codebase. Trigger for prompts like "map this codebase", "document this architecture", "onboard me to this repo", or "create codebase docs". Do not trigger for routine feature implementation, bug fixes, or narrow code edits unless the user asks for repository-level discovery.

日本語の概要は準備中です。原文の説明を表示しています。

jcasnellie69/homelab-config22026年10月12日 更新

Act on user feedback attached to the current session. Use when the user submits feedback on the session's changes via the Submit Feedback button.

日本語の概要は準備中です。原文の説明を表示しています。

jcasnellie69/homelab-config22026年10月12日 更新

Add educational comments to the file specified, or prompt asking for file to comment if one is not provided.

日本語の概要は準備中です。原文の説明を表示しています。

jcasnellie69/homelab-config22026年10月12日 更新

Use when adding, modifying, or reviewing VS Code configuration policies. Covers the full policy lifecycle from registration to export to platform-specific artifacts. Run on ANY change that adds a `policy:` field to a configuration property.

日本語の概要は準備中です。原文の説明を表示しています。

jcasnellie69/homelab-config22026年10月12日 更新

Patterns and techniques for adding governance, safety, and trust controls to AI agent systems. Use this skill when: - Building AI agents that call external tools (APIs, databases, file systems) - Implementing policy-based access controls for agent tool usage - Adding semantic intent classification to detect dangerous prompts - Creating trust scoring systems for multi-agent workflows - Building audit trails for agent actions and decisions - Enforcing rate limits, content filters, or tool restrictions on agents - Working with any agent framework (PydanticAI, CrewAI, OpenAI Agents, LangChain, AutoGen)

日本語の概要は準備中です。原文の説明を表示しています。

jcasnellie69/homelab-config22026年10月12日 更新

jcasnellie69 のスキルをすべて見る

このスキルの問題を報告する