Generated banner for API Design Principles
Generated logo for API Design Principles

API Design Principles

Seth HobsonCommunityCreated by Seth Hobson

  • Skill
  • Guidelines
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.
— the description by Seth Hobson

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to API design, covering core principles for both REST and GraphQL paradigms. It offers best practices for resource modeling, HTTP semantics, schema-first development, versioning, and error handling. Designed for developers and architects, it helps ensure APIs are consistent, developer-friendly, and built to evolve over time.

What it does

  • Defines RESTful resource-oriented architecture and HTTP method semantics.
  • Outlines GraphQL schema-first development and type design patterns.
  • Provides strategies for API versioning and evolution.
  • Details patterns for pagination, filtering, and sorting.
  • Establishes standards for consistent error handling and status codes.
  • Offers guidance on modular schema organization and polymorphism.

When to use it

  • When designing the architecture for a new API service.
  • When refactoring existing endpoints to improve usability and consistency.
  • When establishing organizational standards for API development.
  • During the review phase of an API specification before implementation.
  • When migrating or evaluating between REST and GraphQL paradigms.

Advantages

  • Promotes consistency across API surfaces, reducing developer friction.
  • Encourages scalable design patterns that handle growth and complexity.
  • Provides clear, actionable patterns for common API challenges like pagination.
  • Supports better maintainability through structured versioning and deprecation strategies.

Usage examples

“How should I structure my REST endpoints for a user management system?”
The agent will recommend a resource-oriented approach using plural nouns (e.g., /users) and standard HTTP methods (GET, POST, PUT, PATCH, DELETE) for operations.
“What is the best way to handle pagination in a GraphQL API?”
The agent will explain the Relay Cursor Pagination pattern, providing the necessary schema structure for edges, nodes, and pageInfo.
“How can I ensure consistent error responses across my API?”
The agent will suggest a standardized error payload structure including error codes, messages, and optional details, along with appropriate HTTP status codes.
“Should I use URL or header versioning for my API?”
The agent will compare the two approaches, explaining the trade-offs of each to help you decide based on your team's specific requirements.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/wshobson/api-design-principles/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip api-design-principles.zip -d .agents/skills

Documentation by Seth Hobson

API Design Principles

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers and stand the test of time.

When to Use This Skill

  • Designing new REST or GraphQL APIs

  • Refactoring existing APIs for better usability

  • Establishing API design standards for your team

  • Reviewing API specifications before implementation

  • Migrating between API paradigms (REST to GraphQL, etc.)

  • Creating developer-friendly API documentation

  • Optimizing APIs for specific use cases (mobile, third-party integrations)

Core Concepts

1. RESTful Design Principles

Resource-Oriented Architecture

  • Resources are nouns (users, orders, products), not verbs

  • Use HTTP methods for actions (GET, POST, PUT, PATCH, DELETE)

  • URLs represent resource hierarchies

  • Consistent naming conventions

HTTP Methods Semantics:

  • GET: Retrieve resources (idempotent, safe)

  • POST: Create new resources

  • PUT: Replace entire resource (idempotent)

  • PATCH: Partial resource updates

  • DELETE: Remove resources (idempotent)

2. GraphQL Design Principles

Schema-First Development

  • Types define your domain model

  • Queries for reading data

  • Mutations for modifying data

  • Subscriptions for real-time updates

Query Structure:

  • Clients request exactly what they need

  • Single endpoint, multiple operations

  • Strongly typed schema

  • Introspection built-in

3. API Versioning Strategies

URL Versioning:

/api/v1/users
/api/v2/users

Header Versioning:

Accept: application/vnd.api+json; version=1

Query Parameter Versioning:

/api/users?version=1

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

REST APIs
  1. Consistent Naming: Use plural nouns for collections (/users, not /user)

  2. Stateless: Each request contains all necessary information

  3. Use HTTP Status Codes Correctly: 2xx success, 4xx client errors, 5xx server errors

  4. Version Your API: Plan for breaking changes from day one

  5. Pagination: Always paginate large collections

  6. Rate Limiting: Protect your API with rate limits

  7. Documentation: Use OpenAPI/Swagger for interactive docs

GraphQL APIs
  1. Schema First: Design schema before writing resolvers

  2. Avoid N+1: Use DataLoaders for efficient data fetching

  3. Input Validation: Validate at schema and resolver levels

  4. Error Handling: Return structured errors in mutation payloads

  5. Pagination: Use cursor-based pagination (Relay spec)

  6. Deprecation: Use @deprecated directive for gradual migration

  7. Monitoring: Track query complexity and execution time

Common Pitfalls

  • Over-fetching/Under-fetching (REST): Fixed in GraphQL but requires DataLoaders

  • Breaking Changes: Version APIs or use deprecation strategies

  • Inconsistent Error Formats: Standardize error responses

  • Missing Rate Limits: APIs without limits are vulnerable to abuse

  • Poor Documentation: Undocumented APIs frustrate developers

  • Ignoring HTTP Semantics: POST for idempotent operations breaks expectations

  • Tight Coupling: API structure shouldn't mirror database schema

Files

references/graphql-schema-design.md

GraphQL Schema Design Patterns

Schema Organization

Modular Schema Structure
# user.graphql
type User {
  id: ID!
  email: String!
  name: String!
  posts: [Post!]!
}

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

extend type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

# post.graphql
type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
}

extend type Query {
  post(id: ID!): Post
}

Type Design Patterns

1. Non-Null Types
type User {
  id: ID! # Always required
  email: String! # Required
  phone: String # Optional (nullable)
  posts: [Post!]! # Non-null array of non-null posts
  tags: [String!] # Nullable array of non-null strings
}
2. Interfaces for Polymorphism
interface Node {
  id: ID!
  createdAt: DateTime!
}

type User implements Node {
  id: ID!
  createdAt: DateTime!
  email: String!
}

type Post implements Node {
  id: ID!
  createdAt: DateTime!
  title: String!
}

type Query {
  node(id: ID!): Node
}
3. Unions for Heterogeneous Results
union SearchResult = User | Post | Comment

type Query {
  search(query: String!): [SearchResult!]!
}

# Query example
{
  search(query: "graphql") {
    ... on User {
      name
      email
    }
    ... on Post {
      title
      content
    }
    ... on Comment {
      text
      author {
        name
      }
    }
  }
}
4. Input Types
input CreateUserInput {
  email: String!
  name: String!
  password: String!
  profileInput: ProfileInput
}

input ProfileInput {
  bio: String
  avatar: String
  website: String
}

input UpdateUserInput {
  id: ID!
  email: String
  name: String
  profileInput: ProfileInput
}

Pagination Patterns

type UserConnection {
  edges: [UserEdge!]!
  pageInfo: PageInfo!
  totalCount: Int!
}

type UserEdge {
  node: User!
  cursor: String!
}

type PageInfo {
  hasNextPage: Boolean!
  hasPreviousPage: Boolean!
  startCursor: String
  endCursor: String
}

type Query {
  users(first: Int, after: String, last: Int, before: String): UserConnection!
}

# Usage
{
  users(first: 10, after: "cursor123") {
    edges {
      cursor
      node {
        id
        name
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
Offset Pagination (Simpler)
type UserList {
  items: [User!]!
  total: Int!
  page: Int!
  pageSize: Int!
}

type Query {
  users(page: Int = 1, pageSize: Int = 20): UserList!
}

Mutation Design Patterns

1. Input/Payload Pattern
input CreatePostInput {
  title: String!
  content: String!
  tags: [String!]
}

type CreatePostPayload {
  post: Post
  errors: [Error!]
  success: Boolean!
}

type Error {
  field: String
  message: String!
  code: String!
}

type Mutation {
  createPost(input: CreatePostInput!): CreatePostPayload!
}
2. Optimistic Response Support
type UpdateUserPayload {
  user: User
  clientMutationId: String
  errors: [Error!]
}

input UpdateUserInput {
  id: ID!
  name: String
  clientMutationId: String
}

type Mutation {
  updateUser(input: UpdateUserInput!): UpdateUserPayload!
}
3. Batch Mutations
input BatchCreateUserInput {
  users: [CreateUserInput!]!
}

type BatchCreateUserPayload {
  results: [CreateUserResult!]!
  successCount: Int!
  errorCount: Int!
}

type CreateUserResult {
  user: User
  errors: [Error!]
  index: Int!
}

type Mutation {
  batchCreateUsers(input: BatchCreateUserInput!): BatchCreateUserPayload!
}

Field Design

Arguments and Filtering
type Query {
  posts(
    # Pagination
    first: Int = 20
    after: String

    # Filtering
    status: PostStatus
    authorId: ID
    tag: String

    # Sorting
    orderBy: PostOrderBy = CREATED_AT
    orderDirection: OrderDirection = DESC

    # Searching
    search: String
  ): PostConnection!
}

enum PostStatus {
  DRAFT
  PUBLISHED
  ARCHIVED
}

enum PostOrderBy {
  CREATED_AT
  UPDATED_AT
  TITLE
}

enum OrderDirection {
  ASC
  DESC
}
Computed Fields
type User {
  firstName: String!
  lastName: String!
  fullName: String! # Computed in resolver
  posts: [Post!]!
  postCount: Int! # Computed, doesn't load all posts
}

type Post {
  likeCount: Int!
  commentCount: Int!
  isLikedByViewer: Boolean! # Context-dependent
}

Subscriptions

type Subscription {
  postAdded: Post!

  postUpdated(postId: ID!): Post!

  userStatusChanged(userId: ID!): UserStatus!
}

type UserStatus {
  userId: ID!
  online: Boolean!
  lastSeen: DateTime!
}

# Client usage
subscription {
  postAdded {
    id
    title
    author {
      name
    }
  }
}

Custom Scalars

scalar DateTime
scalar Email
scalar URL
scalar JSON
scalar Money

type User {
  email: Email!
  website: URL
  createdAt: DateTime!
  metadata: JSON
}

type Product {
  price: Money!
}

Directives

Built-in Directives
type User {
  name: String!
  email: String! @deprecated(reason: "Use emails field instead")
  emails: [String!]!

  # Owner-only data: check authorization in the resolver
  privateData: PrivateData
}

# Query
query GetUser($isOwner: Boolean!) {
  user(id: "123") {
    name
    privateData @include(if: $isOwner) {
      ssn
    }
  }
}
Custom Directives
directive @auth(requires: Role = USER) on FIELD_DEFINITION

enum Role {
  USER
  ADMIN
  MODERATOR
}

type Mutation {
  deleteUser(id: ID!): Boolean! @auth(requires: ADMIN)
  updateProfile(input: ProfileInput!): User! @auth
}

Error Handling

Union Error Pattern
type User {
  id: ID!
  email: String!
}

type ValidationError {
  field: String!
  message: String!
}

type NotFoundError {
  message: String!
  resourceType: String!
  resourceId: ID!
}

type AuthorizationError {
  message: String!
}

union UserResult = User | ValidationError | NotFoundError | AuthorizationError

type Query {
  user(id: ID!): UserResult!
}

# Usage
{
  user(id: "123") {
    ... on User {
      id
      email
    }
    ... on NotFoundError {
      message
      resourceType
    }
    ... on AuthorizationError {
      message
    }
  }
}
Errors in Payload
type CreateUserPayload {
  user: User
  errors: [Error!]
  success: Boolean!
}

type Error {
  field: String
  message: String!
  code: ErrorCode!
}

enum ErrorCode {
  VALIDATION_ERROR
  UNAUTHORIZED
  NOT_FOUND
  INTERNAL_ERROR
}

N+1 Query Problem Solutions

DataLoader Pattern
from aiodataloader import DataLoader

class PostLoader(DataLoader):
    async def batch_load_fn(self, post_ids):
        posts = await db.posts.find({"id": {"$in": post_ids}})
        post_map = {post["id"]: post for post in posts}
        return [post_map.get(pid) for pid in post_ids]

# Resolver
@user_type.field("posts")
async def resolve_posts(user, info):
    loader = info.context["loaders"]["post"]
    return await loader.load_many(user["post_ids"])
Query Depth Limiting
from graphql import GraphQLError

def depth_limit_validator(max_depth: int):
    def validate(context, node, ancestors):
        depth = len(ancestors)
        if depth > max_depth:
            raise GraphQLError(
                f"Query depth {depth} exceeds maximum {max_depth}"
            )
    return validate
Query Complexity Analysis
def complexity_limit_validator(max_complexity: int):
    # Checks each field's cost. A limit on the whole query needs a pass that
    # sums these costs over the full document before execution.
    def calculate_complexity(node):
        # Each field = 1, lists multiply
        complexity = 1
        if is_list_field(node):
            complexity *= get_list_size_arg(node)
        if complexity > max_complexity:
            raise GraphQLError(
                f"Query complexity {complexity} exceeds maximum {max_complexity}"
            )
        return complexity

    return calculate_complexity

Schema Versioning

Field Deprecation
type User {
  name: String! @deprecated(reason: "Use firstName and lastName")
  firstName: String!
  lastName: String!
}
Schema Evolution
# v1 - Initial
type User {
  name: String!
}

# v2 - Add optional field (backward compatible)
type User {
  name: String!
  email: String
}

# v3 - Deprecate and add new field
type User {
  name: String! @deprecated(reason: "Use firstName/lastName")
  firstName: String!
  lastName: String!
  email: String
}

Best Practices Summary

  1. Nullable vs Non-Null: Start nullable, make non-null when guaranteed

  2. Input Types: Always use input types for mutations

  3. Payload Pattern: Return errors in mutation payloads

  4. Pagination: Use cursor-based for infinite scroll, offset for simple cases

  5. Naming: Use camelCase for fields, PascalCase for types

  6. Deprecation: Use @deprecated instead of removing fields

  7. DataLoaders: Always use for relationships to prevent N+1

  8. Complexity Limits: Protect against expensive queries

  9. Custom Scalars: Use for domain-specific types (Email, DateTime)

  10. Documentation: Document all fields with descriptions

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Seth Hobson
Publisher
Seth Hobson (Community)
Source
wshobson/agents · plugins/backend-development/skills/api-design-principles · commit 4bde316
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Seth Hobson.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download api-design-principles.zip