SuperAPI AI Directory

api-designer

Coding & development

View repository

Updated 10-15 19:47

About this skill

API Designer

Overview

This SKILL provides a comprehensive guide for designing, documenting, and implementing modern APIs. It covers both REST and GraphQL paradigms, emphasizing industry best practices, clear documentation, and maintainable architecture. Use this SKILL for scalable, secure, and developer-friendly production-ready API design.

Core Capabilities

REST API Design

  • Design resource-oriented endpoints with proper URL structure
  • HTTP method semantics and status code usage
  • Design request/response payloads with consistent naming conventions
  • Pagination, filtering, and sorting strategies
  • Error handling and validation patterns

GraphQL API Design

  • Define schemas including type systems and relationships
  • Design queries and mutations using appropriate input types
  • Resolver patterns and performance optimization
  • Fragment usage and directive implementation
  • Strategies to prevent the N+1 problem

API Documentation

  • Generate OpenAPI 3.0 specifications
  • Interactive documentation via Swagger UI
  • Document authentication and authorization
  • Example requests/responses covering various scenarios
  • Generate code from specifications

Authentication & Authorization

  • OAuth 2.0 flow (authorization code, client credentials, PKCE)
  • JWT token design, validation, and rotation
  • API key management and rotation strategies
  • Implement role-based access control (RBAC)
  • Rate limiting and throttling patterns

API Versioning

  • URL versioning and header-based versioning strategies
  • Semantic versioning for API releases
  • Deprecation planning and communication
  • Maintain backward compatibility
  • Design migration paths

When to Use This Skill

Use this SKILL in the following cases:

  • When designing a new API from scratch or refactoring existing endpoints
  • When generating OpenAPI/Swagger specifications for documentation
  • When implementing authentication and authorization flows
  • When planning API versioning and deprecation strategies
  • When designing GraphQL schemas and resolvers
  • When establishing API governance and best practices

REST API Design Workflow

Step 1: Identify Resources

Identify the core resources (nouns) that the API will expose:

Resources: Users, Posts, Comments

Collections:
- GET    /users              (모든 사용자 목록 조회)
- POST   /users              (새 사용자 생성)

Individual Resources:
- GET    /users/{id}         (특정 사용자 조회)
- PUT    /users/{id}         (사용자 교체 - 전체 업데이트)
- PATCH  /users/{id}         (사용자 업데이트 - 일부 업데이트)
- DELETE /users/{id}         (사용자 삭제)

Nested Resources:
- GET    /users/{id}/posts   (사용자의 포스트 조회)
- POST   /users/{id}/posts   (사용자를 위한 포스트 생성)

Step 2: Design URL Structure

Follow RESTful naming conventions:

Best Practices:

  • Use plural nouns: /users, /posts (/user, /post not)
  • Use hyphens for multiple words: /blog-posts (/blogPosts or /blog_posts not)
  • Keep URLs lowercase
  • Limit nesting to a maximum of 2 levels
  • Use query parameters for filtering: /posts?status=published&author=123

Quick Examples:

✅ Good:
GET /users
GET /users/123/posts
GET /posts?published=true&limit=10

❌ Bad:
GET /getUsers
GET /users/123/posts/comments/likes  (너무 깊은 nesting)
GET /posts/published  (대신 query param 사용)

Step 3: Choose HTTP Methods

Map operations to standard HTTP methods:

  • GET: Retrieve resources - Safe, idempotent, cacheable
  • POST: Create a new resource - Return 201 Created with a Location header
  • PUT: Replace the entire resource - Idempotent, full replacement
  • PATCH: Partial update - update only specific fields
  • DELETE: Resource removal - Idempotent, returns 204 or 200

Step 4: Design Request/Response Payloads

Structure JSON payloads consistently:

Naming Conventions:

  • Use camelCase for JSON field names
  • Use ISO 8601 for timestamps (UTC)
  • Use a consistent ID format with a prefix: usr_, post_
  • Include metadata: createdAt, updatedAt

Example Response:

{
  "id": "usr_1234567890",
  "username": "johndoe",
  "email": "john@example.com",
  "profile": {
    "firstName": "John",
    "lastName": "Doe"
  },
  "createdAt": "2025-10-25T10:30:00Z",
  "updatedAt": "2025-10-25T10:30:00Z"
}

Step 5: Implement Error Handling

Design comprehensive error responses:

Error Response Format:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "details": [
      {
        "field": "email",
        "message": "Email format is invalid"
      }
    ],
    "requestId": "req_abc123xyz",
    "timestamp": "2025-10-25T10:30:00Z"
  }
}

Key Status Codes:

  • 200 OK: Successful GET, PUT, PATCH
  • 201 Created: Successful POST
  • 204 No Content: Successful DELETE
  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Missing/invalid authentication credentials
  • 403 Forbidden: Authenticated but not authorized
  • 404 Not Found: Resource does not exist
  • 422 Unprocessable Entity: Validation error
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error

Step 6: Add Pagination and Filtering

Cursor-Based Pagination (recommended for large datasets):

GET /posts?limit=20&cursor=eyJpZCI6MTIzfQ

Response:
{
  "data": [...],
  "pagination": {
    "nextCursor": "eyJpZCI6MTQzfQ",
    "hasMore": true
  }
}

Offset-Based Pagination (suitable for small datasets):

GET /posts?limit=20&offset=40&sort=-createdAt

Response:
{
  "data": [...],
  "pagination": {
    "total": 500,
    "limit": 20,
    "offset": 40
  }
}

For detailed pagination strategies and filtering patterns, see references/rest_best_practices.md.

GraphQL API Design Workflow

Step 1: Define Schema Types

Generate type definitions for the domain:

type User {
  id: ID!
  username: String!
  email: String!
  profile: Profile
  posts(limit: Int = 10): [Post!]!
  createdAt: DateTime!
}

type Post {
  id: ID!
  title: String!
  content: String!
  published: Boolean!
  author: User!
  tags: [String!]!
  createdAt: DateTime!
}

Step 2: Design Queries

Define query operations including filtering:

type Query {
  user(id: ID!): User
  post(id: ID!): Post

  users(
    limit: Int = 10
    offset: Int = 0
    search: String
  ): UserConnection!

  posts(
    limit: Int = 10
    published: Boolean
    authorId: ID
    tags: [String!]
  ): PostConnection!
}

Step 3: Design Mutations

Define write operations including input types and error handling:

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

input CreateUserInput {
  username: String!
  email: String!
  password: String!
}

type CreateUserPayload {
  user: User
  errors: [Error!]
}

For a complete GraphQL schema example, see examples/graphql_schema.graphql.

Authentication Patterns

OAuth 2.0 Quick Reference

Authorization Code Flow (web app with a backend):

1. client_id, redirect_uri, scope와 함께 /oauth/authorize로 리다이렉트
2. 사용자가 인증하고 권한 부여
3. 리다이렉트를 통해 authorization code 수신
4. /oauth/token에서 코드를 access token으로 교환
5. Authorization header에 access token 사용

Client Credentials Flow (service-to-service communication):

POST /oauth/token
{
  "grant_type": "client_credentials",
  "client_id": "CLIENT_ID",
  "client_secret": "SECRET"
}

PKCE Flow (mobile/SPA - safest for public clients):

1. code_verifier 및 code_challenge 생성
2. code_challenge와 함께 권한 요청
3. code_verifier로 코드를 토큰으로 교환 (client_secret 불필요)

JWT Token Design

Token Structure:

{
  "header": { "alg": "RS256", "typ": "JWT" },
  "payload": {
    "sub": "usr_1234567890",
    "iat": 1698336000,
    "exp": 1698339600,
    "scope": ["read:posts", "write:posts"],
    "roles": ["user", "editor"]
  }
}

Usage:

Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

API Key Authentication

X-API-Key: sk_live_abcdef1234567890

Best Practices:

  • Use different keys per environment (dev, staging, prod)
  • Support multiple keys per account for rotation
  • Implement key expiration and usage logs
  • Do not expose keys in client-side code

For comprehensive authentication patterns including refresh tokens, MFA, and security best practices, see references/authentication.md.

API Versioning Strategies

URL Versioning (recommended)

/v1/users
/v2/users

Pros: Clear and explicit, easy caching and routing Cons: URL proliferation, managing multiple codebases

Header Versioning

Accept: application/vnd.myapi.v2+json
API-Version: 2

Pros: Clean URLs, maintain the same endpoint Cons: Less visible, harder to test in the browser

When to Version

When a new version is needed:

  • Deleting an endpoint or field
  • Changing a field type or name
  • Modifying the authentication method
  • Violating an existing client contract

When versioning is not needed:

  • Adding a new optional field
  • Adding a new endpoint
  • Bug fixes or performance improvements

For detailed versioning strategies, deprecation processes, and migration patterns, see references/versioning-strategies.md.

OpenAPI Specification

Basic Structure

openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
  description: API description

servers:
  - url: https://api.example.com/v1

paths:
  /users:
    get:
      summary: List users
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 10
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'

components:
  schemas:
    User:
      type: object
      required:
        - username
        - email
      properties:
        id:
          type: string
        username:
          type: string
        email:
          type: string
          format: email

For a complete OpenAPI specification example, see examples/openapi_spec.yaml.

Generating Documentation

Generate and validate the specification using the helper script:

# 코드에서 OpenAPI 사양 생성
python scripts/api_helper.py generate --input api.py --output openapi.yaml

# 기존 사양 검증
python scripts/api_helper.py validate --spec openapi.yaml

# 문서 사이트 생성
python scripts/api_helper.py docs --spec openapi.yaml --output docs/

Best Practices Summary

Consistency

  • Use consistent naming conventions across all endpoints
  • Standardize the error response format
  • Apply the same authentication pattern everywhere
  • Use a unified timestamp format (ISO 8601 with UTC)

Security

  • Always use HTTPS in Production
  • Thoroughly validate all input data
  • Implement Rate limiting per user/key/IP
  • Use appropriate authentication for all endpoints
  • Do not expose sensitive data in URLs or logs
  • Implement proper CORS configuration

Performance

  • Use Pagination for large datasets
  • Implement caching headers (ETag, Cache-Control)
  • Support compression (gzip)
  • Use Cursor-based pagination for real-time data
  • Implement field selection (Field selection) for Sparse fieldsets

Documentation

  • Document all endpoints with OpenAPI
  • Provide Example requests and responses
  • Document error codes and their meanings
  • Include authentication guidance
  • Keep documentation in sync with the code

Maintainability

  • Properly version the API with a clear deprecation schedule
  • Provide deprecation warnings before removing features
  • Write integration tests for all endpoints
  • Monitor API usage, errors, and performance
  • Maintain Backward compatibility where possible

Common Patterns

Health Check

GET /health
Response: { "status": "ok", "timestamp": "2025-10-25T10:30:00Z" }

Batch Operations

POST /users/batch
{
  "operations": [
    { "method": "POST", "path": "/users", "body": {...} },
    { "method": "PATCH", "path": "/users/123", "body": {...} }
  ]
}

Webhooks

POST /webhooks/configure
{
  "url": "https://your-app.com/webhook",
  "events": ["user.created", "post.published"],
  "secret": "webhook_secret_key"
}

For additional patterns including Idempotency, long-running operations, file uploads, and soft deletes, see references/common-patterns.md.

Quick Reference Checklists

REST Endpoint Design

  • Use plural nouns for collections
  • Limit URL nesting to 2 levels
  • Use appropriate HTTP methods
  • Return accurate status codes
  • Implement a consistent error format
  • Add Pagination to collections
  • Include Filtering and sorting
  • Document with OpenAPI
  • Implement Authentication
  • Add Rate limiting

GraphQL Schema Design

  • Define a clear type hierarchy
  • Use Nullable types appropriately
  • Implement Pagination (connections)
  • Design mutations using Input types
  • Return errors in the Payload
  • Document the schema with descriptions (Description)
  • Implement Authentication/authorization
  • Optimize N+1 queries (DataLoader)

Additional Resources

Comprehensive References

  • references/rest_best_practices.md - Full REST API patterns, status codes, and implementation details
  • references/authentication.md - OAuth 2.0, JWT, API keys, MFA, and security best practices
  • references/versioning-strategies.md - Versioning approaches, deprecation, and migration strategies
  • references/common-patterns.md - Health check, webhooks, batch operations 등

Examples

  • examples/openapi_spec.yaml - Full OpenAPI 3.0 specification for the blog API
  • examples/graphql_schema.graphql - Full GraphQL schema including queries, mutations, and subscriptions

Tools

  • scripts/api_helper.py - Utilities for generating, validating, and documenting API specifications