Agent skill

API Patterns

by softspark in softspark/ai-toolkit

API design: naming, versioning, pagination, idempotency, OpenAPI, error contracts and safe retries.

Apache-2.0Auto-check passedBackend & APIs

Install API Patterns

skills CLI
$ npx skills add softspark/ai-toolkit --skill api-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install softspark/ai-toolkit api-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/softspark/ai-toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/app/skills/api-patterns .claude/skills/api-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
api-patterns
GitHub stars
179
Token cost
~3.5k tokens
SKILL.md length
1,111 words
Files
2
Skills in repo
112
Repo updated
First seen
Licence
Apache-2.0

At a glance

API design: naming, versioning, pagination, idempotency, OpenAPI, error contracts and safe retries.

  • Tasks that involve OpenAPI specifications
  • SKILL.md covers REST API Design, FastAPI Implementation, Parameter Documentation… and JSON-RPC 2.0 (MCP Pattern), plus 6 more sections
  • Needs API_KEY and JWT_SECRET
  • Tasks that involve API design

What it does

API Patterns is an agent skill from softspark/ai-toolkit. API design: naming, versioning, pagination, idempotency, OpenAPI, error contracts and safe retries. Triggers: API design, REST, GraphQL, OpenAPI, Swagger, error response, HTTP status, rate limit.

Its SKILL.md is about 3.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files (for example `reference/error-contracts.md`).

It sits in Backend & APIs, covering OpenAPI specifications, API design and Rate limiting. It works with OpenAPI and GraphQL. The repository describes itself as: Professional-grade AI coding toolkit: 94 skills, 44 agents, multi-platform (Claude, Cursor, Windsurf, Copilot, Gemini, Cline, Roo Code, Aider, Augment, Antigravity, Codex CLI… The licence is Apache-2.0.

When your agent uses it

  • Tasks that involve OpenAPI specifications
  • Tasks that involve API design
  • Tasks that involve Rate limiting

Example prompts

  • “/api-patterns”

Requirements

  • Python 3
  • A credential in API_KEY
  • A credential in JWT_SECRET
  • Pre-approved tools (allowed-tools): Read

What it can do on your machine

Read from SKILL.md and the folder at commit d64db2b. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are json and python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • ajv.js.org
    • json-schema.org

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • API_KEY
    • JWT_SECRET

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

API Patterns loads about 3.5k tokens when it runs. Until then it costs about 52 tokens; SKILL.md has 1,111 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~52
When it runs · the whole SKILL.md, loaded when a task matches
~3.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from softspark/ai-toolkit at commit d64db2b, republished under its Apache-2.0 licence (© softspark). 1,111 words, ~3,543 tokens.

Download SKILL.mdSave it as .claude/skills/api-patterns/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
api-patterns
description
API design: naming, versioning, pagination, idempotency, OpenAPI, error contracts and safe retries. Triggers: API design, REST, GraphQL, OpenAPI, Swagger, error response, HTTP status, rate limit.
allowed-tools
Read
effort
medium
user-invocable
false

API Patterns Skill

REST API Design

Resource Naming
# Collection
GET    /api/v1/documents        # List documents
POST   /api/v1/documents        # Create document

# Single resource
GET    /api/v1/documents/{id}   # Get document
PUT    /api/v1/documents/{id}   # Replace document
PATCH  /api/v1/documents/{id}   # Update document
DELETE /api/v1/documents/{id}   # Delete document

# Nested resources
GET    /api/v1/users/{id}/documents  # User's documents
HTTP Status Codes
CodeMeaningWhen to Use
200OKSuccessful GET/PUT/PATCH
201CreatedSuccessful POST
204No ContentSuccessful DELETE
400Bad RequestMalformed request or an established domain refusal
401UnauthorizedMissing/invalid auth
403ForbiddenNo permission
404Not FoundResource doesn't exist
405Method Not AllowedUnsupported method; preserve Allow
409ConflictDuplicate resource or current-state conflict
412Precondition FailedSupplied concurrency version is stale
422UnprocessableValidation error
428Precondition RequiredRequired concurrency precondition is missing
429Too Many RequestsRate limited
500Internal ErrorServer error
503Service UnavailableDependency temporarily unavailable
Response Format

Follow the host's existing resource and collection contract. This envelope is illustrative; do not impose it on a framework that already defines another shape.

json
{
  "data": {
    "id": "123",
    "type": "document",
    "attributes": {
      "title": "Example",
      "content": "..."
    }
  },
  "meta": {
    "total": 100,
    "page": 1,
    "per_page": 10
  }
}
Error Response

Use the established error representation, which may be problem details, framework validation errors, or a domain-specific envelope like this example:

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input",
    "details": [
      {"field": "title", "message": "Title is required"},
      {"field": "limit", "message": "Must be between 1 and 100"}
    ]
  }
}

When implementing or reviewing failure paths, read Error contracts and safe retries. Classify from the original cause, preserve public codes and JSON types, and distinguish an unknown operation outcome from a confirmed refusal. Do not turn arbitrary server failures into invalid-input responses.

When adding client-side validation, read reference/input-validation.md from the installed security-patterns skill. Resolve that skill through the current client's catalog, since adapters may namespace skill directory names. Use one authoritative rule source and prove parity at the request boundary.


FastAPI Implementation

python
from fastapi import FastAPI, HTTPException, Query, Path
from pydantic import BaseModel, Field

app = FastAPI(title="RAG-MCP API", version="1.0.0")

class InvalidSearchQuery(Exception):
    """Known request-level refusal from the application-owned search adapter."""

class SearchRequest(BaseModel):
    query: str = Field(..., min_length=1, description="Search query")
    limit: int = Field(10, ge=1, le=100, description="Max results")

class SearchResult(BaseModel):
    id: str
    title: str
    score: float
    content: str

class SearchResponse(BaseModel):
    results: list[SearchResult]
    total: int

@app.post("/api/v1/search", response_model=SearchResponse)
async def search(request: SearchRequest):
    """Search the knowledge base.

    Args:
        request: Search parameters

    Returns:
        Search results with scores
    """
    try:
        results = await perform_search(request.query, request.limit)
        return SearchResponse(results=results, total=len(results))
    except InvalidSearchQuery as exc:
        raise HTTPException(
            status_code=400,
            detail="The search query is not supported. Check its syntax.",
        ) from exc

Parameter Documentation Conventions

The same rules apply to OpenAPI description fields, Pydantic Field(description=...), and MCP tool parameters: the description should encode the workflow, not just restate the type. A consumer (human or LLM) reads it to know how to supply a valid value, not what language primitive it is.

Prefer enums with per-value descriptions for closed sets

A free-form string for status forces the caller to guess valid values. Constrain it and document each one:

python
class ListReposRequest(BaseModel):
    visibility: Literal["PUBLIC", "PRIVATE", "INTERNAL"] = Field(
        "PUBLIC",
        description=(
            "Repository visibility filter. "
            "PUBLIC = visible to anyone; "
            "PRIVATE = only members with explicit access; "
            "INTERNAL = visible to all org members (Enterprise only)."
        ),
    )

In OpenAPI, pair enum with the value meanings in the description (or x-enum-descriptions if your tooling renders it). Avoid documenting a closed set as plain string — the caller cannot tell INTERNAL is valid but internal is not.

Encode cross-field dependencies in the description

Document cross-field requirements where the dependent field is defined and encode them in the supported schema dialect. JSON Schema supports conditional requirements with dependentRequired or if/then; application state and opaque-token provenance still require prose and runtime checks. See conditional schema validation.

python
cursor: str | None = Field(
    None,
    description=(
        "Pagination cursor. Requires a `next_cursor` value obtained from a prior "
        "GET /api/v1/documents response. Omit on the first page; do not synthesize."
    ),
)

State the source call by name (next_cursor from the previous list response), not just "an opaque token".

Add provenance and exactness constraints for opaque IDs

Opaque identifiers (resource IDs, idempotency keys, cursors) are the most common source of bad calls because they look like something the caller can invent. Pin them down:

python
document_id: str = Field(
    ...,
    description=(
        "Exact document id, e.g. `doc_9f3a21`. Copy it verbatim from a search or "
        "list response — case-sensitive, do not type from memory or guess the format. "
        "Obtain it from GET /api/v1/documents or the search results."
    ),
)

The two load-bearing phrases: where it comes from (from a search or list response) and how to handle it (copy verbatim, case-sensitive, do not type from memory). Both belong in the description, not a separate doc.

Descriptions encode workflow, not type
WeakStrong
id: The document idid: Exact document id (e.g. doc_9f3a21), copied verbatim from a list/search response — case-sensitive
status: The status stringstatus: One of OPEN, MERGED, CLOSED (see per-value meanings); filters the result set
cursor: Pagination cursorcursor: next_cursor from the previous page response; omit on first request
since: A timestampsince: RFC 3339 UTC timestamp; returns records created strictly after it

JSON-RPC 2.0 (MCP Pattern)

Request
json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search",
    "arguments": {"query": "test"}
  }
}
Success Response
json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {"type": "text", "text": "Results..."}
    ]
  }
}
Error Response
json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32602,
    "message": "Invalid params",
    "data": {"field": "query", "message": "Required"}
  }
}

Pagination

Offset-based
GET /api/v1/documents?page=2&per_page=20
json
{
  "data": [...],
  "meta": {
    "total": 150,
    "page": 2,
    "per_page": 20,
    "total_pages": 8
  }
}
GET /api/v1/documents?cursor=abc123&limit=20
json
{
  "data": [...],
  "meta": {
    "next_cursor": "xyz789",
    "has_more": true
  }
}

Rate Limiting

Headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1699999999
Implementation
python
from fastapi import Request
from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)

@app.get("/api/v1/search")
@limiter.limit("100/minute")
async def search(request: Request, query: str):
    ...

Authentication

API Key (Simple)
python
from fastapi import Depends, HTTPException, Security
from fastapi.security import APIKeyHeader

api_key_header = APIKeyHeader(name="X-API-Key")

async def verify_api_key(api_key: str = Security(api_key_header)):
    if api_key != settings.API_KEY:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return api_key

@app.get("/api/v1/protected")
async def protected_endpoint(api_key: str = Depends(verify_api_key)):
    ...
JWT (Production)
python
from fastapi import Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt

security = HTTPBearer()

async def verify_jwt(credentials: HTTPAuthorizationCredentials = Depends(security)):
    try:
        payload = jwt.decode(
            credentials.credentials,
            settings.JWT_SECRET,
            algorithms=["HS256"]
        )
        return payload
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")

Versioning

/api/v1/documents
/api/v2/documents
Header
Accept: application/vnd.myapi.v1+json

Common Rationalizations

ExcuseWhy It's Wrong
"We'll version the API later"Unversioned APIs break clients on every change — version from day one
"Retries are the client's problem"Server-side idempotency prevents data corruption — design for at-least-once delivery
"We'll add rate limiting later"Unprotected endpoints get abused within hours of deployment
"Error messages are just for debugging"Error responses are your API's UX — clients depend on consistent, parseable errors
"PATCH and PUT are the same thing"PUT replaces the resource, PATCH modifies it — wrong semantics cause data loss
Show full SKILL.md (443 more words)Show less

Hard Rules

  • MUST version the API from day one (URL path or Accept header) — unversioned APIs break clients on every change
  • MUST validate input type, format and size at the API boundary; enforce state-dependent domain invariants in business logic as well
  • MUST use PUT for full replacement and PATCH for partial update — confusing the two causes silent data loss
  • NEVER return unbounded list responses — pagination (offset or cursor) is mandatory
  • NEVER expose private implementation details in ordinary API errors, including 4xx and background-job error fields; preserve the host's public error representation
  • CRITICAL: idempotency on POST/PUT/PATCH is non-negotiable when retries are possible — accept an Idempotency-Key header or design the endpoint to be naturally idempotent
  • CRITICAL: rate limits exist from the first deploy, not "later" — unprotected endpoints get abused within hours

Best Practices

  • Use HTTPS only
  • Version your API
  • Validate all inputs
  • Use proper HTTP methods and status codes
  • Implement rate limiting
  • Include pagination for lists
  • Return consistent error format
  • Document with OpenAPI/Swagger
  • Log requests for debugging
  • Set reasonable timeouts

Gotchas

  • CDN and load-balancer caches key on the full URL by default. If you version via both URL path and Accept header (e.g., /api/v1/... + Accept: application/vnd.myapi.v2+json), the edge returns the wrong payload for non-path versioning. Pick one versioning axis and stick to it.
  • A published OpenAPI schema does not prove request enforcement. Ajv enforces additionalProperties: false when that schema is executed; its strict mode checks schema correctness and does not change validation results. Verify that the request boundary runs the intended schema and test unknown fields. See Ajv strict mode and additionalProperties.
  • Idempotency-Key only works if the server persists the mapping from key to response — purely in-memory implementations forget it on restart. Back it with Redis or the primary DB.
  • HTTP methods are case-sensitive per RFC 7230 (all uppercase); some clients and proxies normalize, some don't. A post method reaches the server as-is through some edge proxies and hits a 405 instead of the POST route.
  • Give rate-limited callers a meaningful Retry-After. For 503, include it when the server can provide a credible retry window; do not invent an outage duration. A retry header does not prove that repeating a write is safe.

When NOT to Load

  • For MCP protocol (JSON-RPC over stdio/SSE) specifics — use /mcp-patterns; this skill covers generic JSON-RPC only
  • For gRPC, GraphQL subscriptions, or message queues — outside scope; this skill is REST-first with a JSON-RPC aside
  • For language-specific idioms (Fastify middleware chains, ASP.NET minimal APIs, etc.) — pair this skill with /typescript-patterns, /csharp-patterns, etc.
  • For OpenAPI schema authoring as the primary task — use /docs with OpenAPI output; this skill is design-only
  • For authentication deep-dives beyond the starter API-key and JWT snippets — use /security-patterns

© softspark, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in app/skills/api-patterns of softspark/ai-toolkit.

  • SKILL.md
  • reference/error-contracts.md

Open the folder on GitHubat commit d64db2b

Compare with similar skills

API Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

API Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
API Patterns this skillsoftspark/ai-toolkit179—~3.5kAutomated safety check: PassApache-2.0
API Architectcuriositech/some_claude_skills2431 repos~1.4kAutomated safety check: PassMIT
API ForgeEliasOulkadi/shokunin114—~2.9kAutomated safety check: PassMIT
API DesignerJeffallan/claude-skills12k2 repos~2kAutomated safety check: PassMIT
API Designyonatangross/orchestkit289—~2.9kAutomated safety check: PassMIT
API Contract Detectionprime-radiant-inc/greenfield292—~4.2kAutomated safety check: PassApache-2.0

Similar skills

  • API Architect

    curiositech/some_claude_skills

    Expert API designer for REST, GraphQL, gRPC architectures. An agent skill from curiositech/some_claude_skills.

    243 GitHub starsUsed in 1 repo~1.4k tokens
    Backend & APIsAuto-check passed
  • API Forge

    EliasOulkadi/shokunin

    Design REST/GraphQL APIs with OpenAPI 3.1, error handling, pagination, rate limiting, webhooks, and idempotency.

    114 GitHub stars~2.9k tokensUpdated 3 days ago
    Backend & APIsAuto-check passed
  • API Designer

    Jeffallan/claude-skills

    Designs REST and GraphQL APIs from resource modeling to an OpenAPI 3.1 contract, with versioning, pagination and RFC 7807 error handling.

    12k GitHub starsUsed in 2 repos~2k tokens
    Backend & APIsAuto-check passed
  • API Design

    yonatangross/orchestkit

    API contract design for REST and GraphQL, covering resource shape, URL and header versioning with deprecation windows, RFC 9457 Problem Details error handling, and OpenAPI specs.

    289 GitHub stars~2.9k tokensUpdated today
    Backend & APIsAuto-check passed
  • API Contract Detection

    prime-radiant-inc/greenfield

    Finds OpenAPI, GraphQL, Protobuf and JSON Schema files in a codebase and extracts behavioral claims from them as part of a reverse-engineering workflow.

    292 GitHub stars~4.2k tokensUpdated 2 mo ago
    Backend & APIsAuto-check passed
  • Implementing API Patterns

    ancoleman/ai-design-components

    API design and implementation across REST, GraphQL, gRPC, and tRPC patterns.

    526 GitHub starsUsed in 1 repo~3k tokens
    Backend & APIsAuto-check passed

More from softspark/ai-toolkit

All 112 skills in this repo
  • Prepare Test Env

    softspark/ai-toolkit

    Prepare or verify a project QA environment with source identity, readiness, browser access, evidence paths and owned cleanup.

    179 GitHub stars~1.8k tokensUpdated yesterday
    Auto-check: notes
  • A11y Validate

    softspark/ai-toolkit

    Accessibility validator: WCAG 2.1 AA, EN 301 549, EAA. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~3.8k tokensUpdated yesterday
    Auto-check: notes
  • Analyze

    softspark/ai-toolkit

    Analyzes code quality, complexity, patterns across codebase.

    179 GitHub stars~1k tokensUpdated yesterday
    Auto-check passed
  • Autonomous Dev

    softspark/ai-toolkit

    Drives a brief, specification, issue or existing PR through implementation, review, tests and QA to a ready PR.

    179 GitHub stars~2.6k tokensUpdated yesterday
    Auto-check: notes
  • Brand Voice

    softspark/ai-toolkit

    Direct technical voice for docs, README, user-facing text. An agent skill from softspark/ai-toolkit.

    179 GitHub stars~2.1k tokensUpdated yesterday
    Auto-check passed
  • CI

    softspark/ai-toolkit

    Detect/generate/debug CI pipeline config (GitHub Actions, GitLab CI).

    179 GitHub stars~1.1k tokensUpdated yesterday
    Auto-check: notes

Works with

Categories

Questions about API Patterns

What does API Patterns do?

API design: naming, versioning, pagination, idempotency, OpenAPI, error contracts and safe retries. API Patterns is an agent skill from softspark/ai-toolkit. API design: naming, versioning, pagination, idempotency, OpenAPI, error contracts and safe retries.

When should I use API Patterns?

API Patterns fits situations like: tasks that involve OpenAPI specifications; tasks that involve API design; tasks that involve Rate limiting.

How do I install API Patterns in Claude Code?

Run `npx skills add softspark/ai-toolkit --skill api-patterns -a claude-code`. Or copy the skill folder (app/skills/api-patterns in softspark/ai-toolkit) into .claude/skills/api-patterns in your project. Claude Code loads it when a task matches its description.

How do I install API Patterns in Codex?

Run `npx skills add softspark/ai-toolkit --skill api-patterns -a codex`. Or copy the skill folder (app/skills/api-patterns in softspark/ai-toolkit) into .agents/skills/api-patterns in your project. Codex loads it when a task matches its description.

Can I use API Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add softspark/ai-toolkit --skill api-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/api-patterns, .gemini/skills/api-patterns, .github/skills/api-patterns and .opencode/skills/api-patterns in your project.

What does API Patterns need to run?

Going by SKILL.md and its folder, API Patterns needs credentials named API_KEY and JWT_SECRET. Our summary lists: Python 3; A credential in API_KEY; A credential in JWT_SECRET. Its frontmatter pre-approves these tools: Read.

Does API Patterns access the network?

SKILL.md names 2 domains. As links in the text: ajv.js.org and json-schema.org. This is read from the text; nothing was executed.

Is API Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does API Patterns use?

API Patterns is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does API Patterns use?

About 3.5k tokens (SKILL.md is roughly 14k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to API Patterns?

Skills that share tags, products or a category with API Patterns: API Architect (curiositech/some_claude_skills, 243 stars), API Forge (EliasOulkadi/shokunin, 114 stars), API Designer (Jeffallan/claude-skills, 12k stars) and API Design (yonatangross/orchestkit, 289 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains API Patterns?

softspark (a GitHub user) maintains it in softspark/ai-toolkit, which has 179 GitHub stars. The repository holds 112 skills in this directory. The repository was last updated on October 7, 2026.

Source: softspark/ai-toolkit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.