agentleFS
vndeevndee/engineering-skills/.claude/skills/api-design/SKILL.md

api-design

Skill3 starsChanged 8 months agoMITView on GitHub

Use when designing new API endpoints, reviewing API consistency, or establishing REST conventions for Go/Fiber or Python/FastAPI backends

125 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use data-modeling, microservices and 8 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • mmondoraSkill

    data-modeling

    Schema design, multi-tenant data isolation, and migration management. Firestore and PostgreSQL patterns, RLS, UUID v7 conventions. Use when designing database schemas, writing migrations, or implementing multi-tenant data access.

    Also in 7 projects that use this

  • pluginagentmarketplaceSkill

    microservices

    Microservices architecture patterns and best practices. Service decomposition, inter-service communication, and distributed data management.

    Also in 4 projects that use this

  • kevinaimonsterSkill

    typescript-strict

    TypeScript strict mode and advanced type system assistant. Helps write strictly-typed TypeScript code with generics, type guards, utility types, conditional types, mapped types, and template literal types. Trigger when user says 'TypeScript types' 'type gymnastics' 'TypeScript generics' 'strict TypeScript' 'type guard' 'TS类型' 'TypeScript严格模式' '类型体操' '泛型怎么写' 'TS type help'. Keywords: TypeScript, strict mode, generics, type guard, utility types, conditional types, mapped types, template literal types, infer, extends, keyof, typeof, type narrowing, discriminated unions, type assertion, type predicate, type gymnastics, TS, 类型体操, 泛型, 类型守卫, 严格类型

    Also in 4 projects that use this

  • InfopibeSkill

    deployment-patterns

    Deployment workflows, CI/CD pipeline patterns, Docker containerization, health checks, rollback strategies, and production readiness checklists for web applications.

    Also in 10 projects that use this

  • DatabricksSkill

    load-testing

    Load test a Databricks App to find its maximum QPS. Use when: (1) User says 'load test', 'benchmark', 'QPS', 'throughput', or 'performance test', (2) User wants to find how many queries per second their app can handle, (3) User wants to set up load testing scripts for their agent, (4) User wants to view load test results/dashboard, (5) User wants to validate results or observe latency/error rate with MLflow tracing.

    Also in 4 projects that use this

  • CloudAI-XSkill

    database-design

    Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases. Use when designing tables, optimizing queries, fixing N+1 problems, planning migrations, or when asked about database performance, normalization, ORMs, or data modeling.

    Also in 15 projects that use this

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 0 are distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 104 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every Go handler MUST have swaggo annotations.

    line 224
  2. Very specific:

    Every handler function gets a godoc comment block:

    line 254
  3. Very specific:

    Add example tags for better Swagger UI:

    line 292
  4. Very specific:

    REQUIRED: Update CLAUDE.md with API conventions (claude-md)

    line 328

“Common” is measured: kept by at least 6 in 10 of the 104 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

API Design Patterns

Overview

Consistent REST API conventions for Go/Fiber and Python/FastAPI backends. Covers URL structure, response envelopes, error handling, and middleware.

Core principle: APIs should be predictable. Same patterns everywhere, every time.

When to Use

  • Designing new endpoints
  • Reviewing API consistency across services
  • Setting up middleware ordering
  • Establishing error response formats

URL Conventions

GET    /api/v1/resources          # List (paginated)
POST   /api/v1/resources          # Create
GET    /api/v1/resources/:id      # Get by ID
PUT    /api/v1/resources/:id      # Full update
PATCH  /api/v1/resources/:id      # Partial update
DELETE /api/v1/resources/:id      # Delete

# Nested resources (max 1 level deep)
GET    /api/v1/users/:id/posts    # User's posts
POST   /api/v1/users/:id/posts    # Create post for user

# Actions (when CRUD doesn't fit)
POST   /api/v1/resources/:id/archive
POST   /api/v1/resources/:id/send

Response Envelope

// Success
{
    "success": true,
    "message": "Operation completed successfully"
}

// Success (paginated list)
{
    "items": [ ... ],
    "pagination": {
        "limit": 20,
        "offset": 0,
        "total": 100
    }
}

// Error
{
    "code": "validation_error",
    "message": "Validation failed",
    "details": [
        { "field": "email", "message": "email is required" }
    ]
}

Go Response Types

// pkg/response.go
type SuccessResponse struct {
    Success bool   `json:"success"`
    Message string `json:"message"`
}

type PaginationResponse struct {
    Limit  int `json:"limit"`
    Offset int `json:"offset"`
    Total  int `json:"total"`
}

type PaginatedResponse struct {
    Items      interface{}        `json:"items"`
    Pagination PaginationResponse `json:"pagination"`
}

type ErrorResponse struct {
    StatusCode int          `json:"-"`
    Code       string       `json:"code"`
    Message    string       `json:"message"`
    Details    []FieldError `json:"details,omitempty"`
}

type FieldError struct {
    Field   string `json:"field"`
    Message string `json:"message"`
}

HTTP Status Mapping

StatusWhen
200Successful GET, PUT, PATCH
201Successful POST (created)
204Successful DELETE
400Validation error, malformed request
401Missing/invalid authentication
403Authenticated but unauthorized
404Resource not found
409Conflict (duplicate, state conflict)
422Valid syntax but unprocessable
429Rate limited
500Internal server error

Go/Fiber Specifics

Middleware ordering:

app.Use(logger.New())
app.Use(recover.New())
app.Use(cors.New(cors.Config{
    AllowOrigins: "http://localhost:5173",
}))
app.Use(requestid.New())
// auth middleware on protected routes only

Handler pattern (using generic validator from pkg/validator.go):

func (h *Handler) Create(c fiber.Ctx) error {
    body, err := pkg.ValidateBody[CreateUserRequest](c)
    if err != nil {
        return err
    }
    result, err := h.useCase.Execute(c.Context(), body.ToDomain())
    if err != nil {
        return mapDomainError(err)
    }
    return c.Status(201).JSON(result.ToResponse())
}

func (h *Handler) List(c fiber.Ctx) error {
    query, err := pkg.ValidateQuery[ListUsersQuery](c)
    if err != nil {
        return err
    }
    items, total, err := h.useCase.List(c.Context(), query.Limit, query.Offset)
    if err != nil {
        return mapDomainError(err)
    }
    return c.JSON(pkg.PaginatedResponse{
        Items:      items,
        Pagination: pkg.PaginationResponse{Limit: query.Limit, Offset: query.Offset, Total: total},
    })
}

Generic validation functions (see pkg/validator.go):

  • ValidateBody[T](c) — parse + validate JSON body, reject unknown fields, apply defaults
  • ValidateQuery[T](c) — parse + validate query params, handle comma-separated slices
  • ValidateParams[T](c) — parse + validate path params
  • ValidateHeader[T](c) — parse + validate headers

Uses go-playground/validator/v10 with struct tags + custom validators. Supports default tag for zero-value defaults.

Request struct example:

type CreateUserRequest struct {
    Email string `json:"email" validate:"required,email"`
    Name  string `json:"name" validate:"required,min=2,max=100"`
    Role  string `json:"role" validate:"omitempty,oneof=admin member viewer" default:"member"`
}

type ListUsersQuery struct {
    Limit  int    `query:"limit" validate:"omitempty,min=1,max=100" default:"20"`
    Offset int    `query:"offset" validate:"omitempty,min=0" default:"0"`
    Search string `query:"search" validate:"omitempty,max=200"`
}

Python/FastAPI Specifics

Dependency injection:

async def get_db(request: Request) -> AsyncGenerator[AsyncSession, None]:
    async with request.app.state.session_factory() as session:
        yield session

@router.post("/users", status_code=201, response_model=UserResponse)
async def create_user(
    body: CreateUserRequest,
    db: AsyncSession = Depends(get_db),
    use_case: CreateUserUseCase = Depends(get_create_user_use_case),
) -> UserResponse:
    result = await use_case.execute(body.to_domain())
    return UserResponse.from_domain(result)

Error handling:

@app.exception_handler(DomainError)
async def domain_error_handler(request: Request, exc: DomainError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": {"code": exc.code, "message": str(exc)}},
    )

Pagination

Offset-based (standard pattern):

GET /api/v1/users?limit=20&offset=0
GET /api/v1/users?limit=20&offset=20

Response includes pagination object with limit, offset, total for client-side page calculation.

Swagger Documentation (swaggo)

Every Go handler MUST have swaggo annotations. Generate with swag init -g cmd/api/main.go -o docs.

main.go Annotations

import (
    swaggo "github.com/gofiber/contrib/v3/swaggo"
    _ "project/docs" // generated swagger docs
)

// @title Project API
// @version 1.0
// @description Project API documentation
// @host localhost:8000
// @BasePath /
// @schemes http

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.

func main() {
    // ...
    app.Get("/docs/*", swaggo.New(swaggo.Config{}))
}

Handler Annotations

Every handler function gets a godoc comment block:

// CreateUser godoc
// @Summary Create a new user
// @Description Create a new user account
// @Tags users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body dto.CreateUserRequest true "Create user request"
// @Success 201 {object} dto.UserResponse
// @Failure 400 {object} pkg.ErrorResponse "Validation error"
// @Failure 401 {object} pkg.ErrorResponse "Unauthorized"
// @Failure 409 {object} pkg.ErrorResponse "Duplicate email"
// @Failure 500 {object} pkg.ErrorResponse "Internal server error"
// @Router /api/v1/users [post]
func (h *Handler) CreateUser(c fiber.Ctx) error { ... }

// ListUsers godoc
// @Summary List users
// @Description Get paginated list of users
// @Tags users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param limit query int false "Limit" default(20)
// @Param offset query int false "Offset" default(0)
// @Param search query string false "Search by name or email"
// @Success 200 {object} pkg.PaginatedResponse{items=[]dto.UserResponse}
// @Failure 401 {object} pkg.ErrorResponse "Unauthorized"
// @Failure 500 {object} pkg.ErrorResponse "Internal server error"
// @Router /api/v1/users [get]
func (h *Handler) ListUsers(c fiber.Ctx) error { ... }

DTO/Response Struct Tags

Add example tags for better Swagger UI:

type UserResponse struct {
    ID    uuid.UUID `json:"id" example:"550e8400-e29b-41d4-a716-446655440000"`
    Email string    `json:"email" example:"user@example.com"`
    Name  string    `json:"name" example:"John Doe"`
    Role  string    `json:"role" example:"member"`
}

Annotation Quick Reference

AnnotationUsage
@SummaryShort description (shown in endpoint list)
@DescriptionDetailed description
@TagsGroup endpoints (e.g., users, system)
@Security BearerAuthRequires auth (omit for public endpoints)
@Param name body Type true "desc"Request body
@Param name path string true "desc"Path parameter
@Param name query int false "desc"Query parameter
@Success 200 {object} TypeSuccess response
@Failure 400 {object} pkg.ErrorResponseError response
@Router /path [method]Route path and HTTP method

CORS for React Dev

Allow-Origin: http://localhost:5173
Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Allow-Headers: Content-Type, Authorization
Allow-Credentials: true

Chains

  • REQUIRED: Update CLAUDE.md with API conventions (claude-md)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.