agentsclimarketplace

Api design

Skill viktorbezdek/skillstack/api-design/skills/api-design

Design production-grade REST, GraphQL, gRPC, and Python library APIs with correct schemas, error contracts, auth, and versioning. Use when the user asks to design an API, define endpoints, create an OpenAPI/Swagger spec, design a GraphQL schema, build a gRPC service, model request/response with Pydantic, add pagination, or review API contracts. NOT for building MCP server tools (use mcp-server). NOT for Node.js/Express API routes or backend patterns (use backend-patterns or typescript-development).From its SKILL.md

Install
npx -y skills add viktorbezdek/skillstack --skill api-design

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

2 things to look at

  • 10 stars10 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
  • runs commandsInstructs the agent to run 3 commands, including `python scripts/api_helper.py validate --spec openapi.yaml` and 2 more.

SKILL.md

11.4 KB, ~2.6k tokens by cl100k_base, as published. Nobody here has run it

API Design

Comprehensive API design skill combining REST, GraphQL, gRPC, and Python library architecture expertise with patterns, templates, and tools for production-grade APIs.

When to Activate

  • Creating new API endpoints (REST, GraphQL, gRPC)
  • Designing resource hierarchies and schemas
  • Writing OpenAPI/Swagger specifications
  • Implementing authentication and authorization
  • Setting up pagination, filtering, and sorting
  • Configuring rate limiting and CORS
  • Designing Python library APIs
  • Reviewing API designs in pull requests

Decision Tree: API Style Selection

What are you building?
+-- CRUD resources with clear entity model? --> REST
|   Best for: resource-oriented operations, caching, wide tooling support
+-- Complex queries with varying client needs? --> GraphQL
|   Best for: over-fetching prevention, nested data, multiple client types
+-- High-throughput service-to-service? --> gRPC
|   Best for: low latency, strong typing, streaming, polyglot microservices
+-- Reusable Python package? --> Python Library API
    Best for: SDKs, internal tooling, developer experience

Quick Reference

RESTful Resource Design

URL Patterns:

  • /api/v1/users (plural nouns, lowercase with hyphens)
  • /api/v1/organizations/{org_id}/teams (hierarchical, max 2 levels)
  • Never use verbs: /getUsers or underscores: /user_profiles

HTTP Methods:

  • GET - Retrieve (safe, idempotent, cacheable)
  • POST - Create (returns 201 with Location header)
  • PUT - Replace entire resource (idempotent)
  • PATCH - Partial update (only changed fields)
  • DELETE - Remove (idempotent, returns 204)

HTTP Status Codes

CategoryCodeWhen
Success200GET, PUT, PATCH success
Success201POST success (include Location header)
Success204DELETE success
Client Error400Malformed request
Client Error401Missing/invalid authentication
Client Error403Insufficient permissions
Client Error404Resource doesn't exist
Client Error409Duplicate resource
Client Error422Validation errors
Client Error429Rate limit exceeded
Server Error500Unhandled exception
Server Error503Database/service down

Error Response Format

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ],
    "requestId": "req_abc123",
    "timestamp": "2025-10-25T10:30:00Z"
  }
}

GraphQL Schema Design

type User {
  id: ID!
  email: String!
  profile: Profile
  posts(first: Int, after: String): PostConnection!
  createdAt: DateTime!
}

type PostConnection {
  edges: [PostEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type Query {
  user(id: ID!): User
  users(first: Int, after: String): UserConnection!
  me: User
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
  updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}

FastAPI Route Pattern

from fastapi import APIRouter, Depends, HTTPException, status

router = APIRouter(prefix="/api/v1/users", tags=["users"])

@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def create_user(
    user_data: UserCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> UserRead:
    """Create a new user in the current tenant."""
    repository = UserRepository(db, tenant_id=current_user.tenant_id)
    user = await repository.create(user_data)
    return user

Pydantic Schema Pattern

from pydantic import BaseModel, EmailStr, Field, ConfigDict

class UserCreate(BaseModel):
    email: EmailStr
    full_name: str = Field(..., min_length=1, max_length=255)
    password: str = Field(..., min_length=8)

class UserRead(BaseModel):
    id: str
    tenant_id: str
    email: EmailStr
    full_name: str
    created_at: datetime
    model_config = ConfigDict(from_attributes=True)

Pagination Patterns

Cursor-Based (recommended for large datasets):

GET /posts?limit=20&cursor=***
{ "data": [...], "pagination": { "nextCursor": "***", "hasMore": true } }

Offset-Based (simpler, for small datasets):

GET /posts?limit=20&offset=40
{ "data": [...], "pagination": { "total": 500, "limit": 20, "offset": 40 } }

Authentication Patterns

FlowUse Case
JWT Bearer tokensAPI authentication, stateless sessions
API Key (X-API-Key)Service-to-service, developer access
OAuth 2.0 Authorization CodeWeb apps with backend
OAuth 2.0 Client CredentialsService-to-service
OAuth 2.0 PKCEMobile/SPA apps

Rate Limiting Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1698340800
Retry-After: 60

Available Resources

References

FileDescription
references/rest-best-practices.mdComprehensive REST API patterns and status codes
references/authentication.mdOAuth 2.0, JWT, API keys, MFA patterns
references/versioning-strategies.mdAPI versioning and deprecation
references/common-patterns.mdHealth checks, webhooks, batch operations
references/schema-patterns.mdGraphQL schema design patterns
references/federation-guide.mdApollo Federation architecture
references/performance-optimization.mdGraphQL performance, DataLoader, caching
references/architectural-principles.mdPython library SOLID principles
references/pep-standards.mdPython PEP quick reference
references/fastapi-setup.mdFastAPI main app configuration
references/openapi.mdOpenAPI customization
references/error-handlers.mdFastAPI exception handlers
references/cors-rate-limiting.mdCORS and rate limiting setup
references/openapi-spec.yamlComplete OpenAPI 3.1 example
references/graphql-schema.graphqlGraphQL with Relay connections
references/grpc-service.protoProtocol Buffer definitions
references/rate-limiting.yamlTier-based rate limit config
references/api-security.yamlAuth, CORS, security headers

Templates

FileDescription
templates/fastapi-crud-endpoint.pyComplete CRUD router template
templates/pydantic-schemas.pyRequest/response schema template
templates/repository-pattern.pyRepository with tenant isolation
templates/rate-limiter.pyUpstash Redis rate limiter
templates/error-handler.pyFastAPI exception handlers
templates/tanstack-server-function.tsTanStack Start server functions

Examples

FileDescription
examples/fastapi-crud.mdCRUD endpoints with repository
examples/pydantic-schemas.mdValidation schema examples
examples/pagination.mdPagination implementation
examples/testing.mdAPI testing patterns
examples/tanstack-start.mdTanStack Start examples
examples/openapi-spec.yamlBlog API OpenAPI specification
examples/graphql-schema.graphqlFull GraphQL schema with subscriptions

Scripts

FileDescription
scripts/schema_analyzer.pyAnalyze GraphQL schemas for quality
scripts/resolver_generator.pyGenerate TypeScript resolvers
scripts/federation_scaffolder.pyScaffold Apollo Federation subgraphs
scripts/api_helper.pyOpenAPI validation and docs generation
scripts/validate-api-spec.shValidate API specifications

Assets (Python Library)

FileDescription
assets/pyproject.toml.templateProduction-ready pyproject.toml
assets/README.md.templateLibrary README template
assets/CONTRIBUTING.md.templateContribution guide
assets/project-structure.txtRecommended package layout
assets/test-structure.txtTest organization
assets/example-exceptions.pyException hierarchy pattern
assets/example-config.pyConfiguration pattern

Checklists

FileDescription
checklists/api-design-checklist.mdAPI design review checklist
checklists/security-review.mdSecurity review checklist

Core Workflows

1. Design a REST API

  1. Identify resources (nouns): Users, Posts, Comments
  2. Design URL structure with proper nesting
  3. Choose appropriate HTTP methods
  4. Define request/response schemas
  5. Document with OpenAPI specification
  6. Implement pagination and filtering
  7. Add authentication and rate limiting

2. Build a GraphQL API

  1. Define schema types with descriptions
  2. Design queries with pagination (Relay connections)
  3. Create mutations with input types and payloads
  4. Implement DataLoader for N+1 prevention
  5. Add authentication in resolvers
  6. Configure caching and complexity limits

3. Validate API Specification

# Validate OpenAPI spec
python scripts/api_helper.py validate --spec openapi.yaml

# Analyze GraphQL schema
python scripts/schema_analyzer.py schema.graphql --validate

# Generate documentation
python scripts/api_helper.py docs --spec openapi.yaml --output docs/

Anti-Patterns

Anti-PatternProblemSolution
Verb-based URLs/getUsers violates REST conventionsUse /users with GET method
Inconsistent response envelopesClients can't parse predictablyAlways use consistent structure
Breaking changes without versioningClients break on updatesUse semantic versioning; deprecation headers
N+1 queries in GraphQLEach resolver fires separate DB queryUse DataLoader for batching
Over-fetching REST endpointsClients get more data than neededSupport sparse fieldsets, filtering
Missing paginationList endpoints return unbounded resultsAlways paginate list endpoints
No idempotency keysDuplicate mutations from retriesAccept Idempotency-Key header
Leaky internal errorsStack traces exposed to clientsGeneric messages in production
Missing CORS configurationBrowser requests blockedConfigure allowed origins explicitly
No rate limitingAPI abuse and DoSImplement per-user/per-endpoint limits
PUT for partial updatesOverwrites unchanged fieldsUse PATCH for partial updates
Monolithic GraphQL schemaSchema becomes unmaintainableUse Federation for schema separation

Quality Checklist

[ ] All endpoints use nouns, not verbs
[ ] Consistent response envelope structure
[ ] Error responses include codes and actionable messages
[ ] Pagination on all list endpoints
[ ] Authentication/authorization documented
[ ] Rate limit headers defined
[ ] Versioning strategy documented
[ ] CORS configured for known origins
[ ] Idempotency keys for mutating operations
[ ] OpenAPI spec validates without errors
[ ] Examples for all request/response types

Version: 1.1.0 Last Updated: 2026-04-18

What ships with it: 48 files

372.8 KB alongside SKILL.md, 13 of them executable

scripts/

8 more files not listed here. See all 48 in the repository.

Keep looking

Skills are one crate of 325,949. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.