CtrlK
BlogDocsLog inGet started
Tessl Logo

moai-ref-api-patterns

REST/GraphQL API design patterns, error handling conventions, and input validation reference for backend development. Agent-extending skill that amplifies backend domain work (spawned via Agent(general-purpose) with backend instructions) with production-grade API patterns. Use when designing APIs, implementing endpoints, or reviewing backend code. NOT for: frontend development, DevOps, database schema design, security audits.

72

Quality

88%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide

SecuritybySnyk

Passed

No findings from the security scan

SKILL.md
Quality
Evals
Security

API Patterns Reference

Target Spawn

Backend domain work spawned via Agent(general-purpose) with backend instructions - Applies these patterns directly to API implementation and review.

RESTful API Design Conventions

PrincipleConventionExample
Resource NamingPlural nouns, lowercase, kebab-case/api/v1/user-profiles
CollectionGET returns array with paginationGET /users?page=1&limit=20
Single ResourceGET returns objectGET /users/{id}
CreatePOST to collectionPOST /users
Update (full)PUT to resourcePUT /users/{id}
Update (partial)PATCH to resourcePATCH /users/{id}
DeleteDELETE to resourceDELETE /users/{id}
Nested ResourcesMax 2 levels deep/users/{id}/posts
FilteringQuery params?status=active&role=admin
SortingSort param?sort=-created_at,name
VersioningURL prefix/api/v1/, /api/v2/

HTTP Status Code Guide

CategoryCodeWhen to Use
Success200 OKSuccessful GET, PUT, PATCH, DELETE
Success201 CreatedSuccessful POST (resource created)
Success204 No ContentSuccessful DELETE (no body)
Client Error400 Bad RequestMalformed request, validation failure
Client Error401 UnauthorizedMissing or invalid authentication
Client Error403 ForbiddenAuthenticated but not authorized
Client Error404 Not FoundResource does not exist
Client Error409 ConflictResource state conflict (duplicate)
Client Error422 UnprocessableValid syntax but semantic error
Client Error429 Too ManyRate limit exceeded
Server Error500 InternalUnexpected server error
Server Error503 Service UnavailableMaintenance or overload

Error Response Format

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Input validation failed",
    "details": [
      {"field": "email", "message": "Must be a valid email address"},
      {"field": "age", "message": "Must be between 0 and 150"}
    ],
    "request_id": "req_abc123"
  }
}

Rules:

  • Never expose stack traces or internal details in production
  • Always include request_id for traceability
  • Use consistent error codes (ENUM, not free text)
  • Login failures: "Invalid email or password" (never reveal which)

Pagination Pattern

{
  "data": [...],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 150,
    "total_pages": 8,
    "has_next": true,
    "has_prev": false
  }
}

For cursor-based (large datasets):

{
  "data": [...],
  "cursor": {
    "next": "eyJpZCI6MTAwfQ==",
    "has_more": true
  }
}

Input Validation Checklist

ValidationMethodTool
Type validationSchema validationZod, Joi, pydantic, Go validator
Length limitsMin/max constraintsSchema min/max
Pattern matchingRegexEmail, URL, phone patterns
Range validationNumber/date boundsmin/max values
EnumerationAllowed valuesenum types
SQL InjectionParameterized queriesORM (Prisma, GORM, SQLAlchemy)
XSSHTML escapingTemplate engines, DOMPurify
Path TraversalPath normalizationfilepath.Clean + whitelist

Rate Limiting Strategy

TargetLimitKey
Auth endpoints5 req/minIP
General API100 req/minUser token
File upload10 req/hourUser token
Public API30 req/minIP

Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After (on 429).

API Versioning Strategy

StrategyUse CaseExample
URL prefixMost APIs/api/v1/users
HeaderInternal APIsAccept: application/vnd.api+json; version=2
Query paramSimple APIs/users?version=2

Breaking changes that require version bump:

  • Removing or renaming fields
  • Changing field types
  • Removing endpoints
  • Changing authentication methods

Non-breaking changes (no version bump needed):

  • Adding new optional fields
  • Adding new endpoints
  • Adding new query parameters

Common Rationalizations

RationalizationReality
"REST naming conventions are just aesthetics"Consistent resource naming is how clients discover and predict endpoints. Inconsistency multiplies documentation burden.
"GraphQL solves over-fetching, so I do not need to design response shapes"GraphQL shifts complexity to the resolver layer. Poorly designed schemas create N+1 queries and authorization gaps.
"Error codes are internal details, clients just need the message"Clients need machine-readable error codes for programmatic handling. Messages are for humans, codes are for code.
"PATCH and PUT are interchangeable"PATCH applies partial updates; PUT replaces the entire resource. Using them incorrectly breaks idempotency expectations.
"I will version the API when it becomes necessary"Versioning after breaking changes forces emergency migrations. Plan versioning from the first release.

Hyrum's Law: Every observable API behavior will eventually be depended on by clients. Undocumented response fields, error formats, and timing characteristics become implicit contracts.

Red Flags

  • API returns different error formats across endpoints
  • Resource names use verbs instead of nouns (e.g., /getUser instead of /users/:id)
  • No pagination on list endpoints that can return unbounded results
  • Breaking change deployed without API version bump
  • GraphQL schema allows unbounded depth or circular queries without limits

Verification

  • All endpoints follow consistent naming convention (nouns, plurals, nested resources)
  • Error responses use a standard format with machine-readable error code
  • List endpoints implement pagination with documented limits
  • API versioning strategy present and enforced (URL path, header, or query param)
  • Breaking vs non-breaking change classification documented for recent changes
  • Input validation returns 400 with specific field-level error details
Repository
modu-ai/moai-adk
Last updated
First committed

Is this your skill?

If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.