Rest api implementation

From FerroxLabs/wayland · View interactive version

Rest api implementation is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level rest api implementation implementation: api-design and frameworks decision frameworks, production-ready patterns, and concrete templates for rest api implementation workflows. Use when the user asks about rest api implementation, rest api implementation configuration, or api-desi

How to use this skill

Skill file

REST API Implementation

When to Use

Use this skill when:

Do NOT use this skill when:


Process

Step 1: Establish the API's Resource Model

Before writing a single endpoint, define the domain resources and their relationships. This is the foundation everything else builds on.

Step 2: Define HTTP Semantics and Method Contracts

Each HTTP method has specific behavioral contracts that clients and intermediaries (proxies, CDNs) rely on. Violating these breaks caching, retry logic, and idempotency assumptions.

Step 3: Design Status Code and Error Response Strategy

Inconsistent status codes and vague error messages are the single most common API usability problem. Define and document a strict contract.

```json

{

"type": "https://api.example.com/errors/validation-failed",

"title": "Request Validation Failed",

"status": 422,

"detail": "The 'email' field must be a valid email address.",

"instance": "/users",

"errors": [

{ "field": "email", "code": "INVALID_FORMAT", "message": "Must match RFC 5322 format" },

{ "field": "birthDate", "code": "FUTURE_DATE", "message": "Birth date cannot be in the future" }

],

"traceId": "01HX4T2Z3M8K9P1Q"

}

```

Step 4: Implement Versioning Strategy

Versioning is a commitment, not an afterthought. Decide before you accept the first external consumer.

Step 5: Implement Authentication, Authorization, and Security Headers

Authentication and authorization are not optional hardening -- they are core API infrastructure.

Step 6: Implement Pagination, Filtering, and Sorting

Collection endpoints must support pagination from day one. Retrofitting pagination onto an unpaginated API breaks existing clients.

Step 7: Implement Caching, Idempotency, and Async Patterns

These three capabilities define the reliability profile of a production API.

Caching:

Idempotency:

Async operations:

```json

{ "jobId": "job_01HX4T2Z", "status": "pending", "statusUrl": "/jobs/job_01HX4T2Z" }

```

Step 8: Generate and Maintain OpenAPI Documentation

Documentation is not separate from implementation -- it is part of the API contract.


Output Format

When helping a user design or review a REST API, structure your response as follows:

## REST API Design Review: [API Name]

### Resource Model

| Resource          | URL Pattern                          | Parent         | ID Type |
|-------------------|--------------------------------------|----------------|---------|
| Users             | /v1/users                            | --             | UUID v4 |
| Orders            | /v1/orders                           | --             | UUID v4 |
| Order Line Items  | /v1/orders/{orderId}/line-items      | Order          | UUID v4 |
| Products          | /v1/products                         | --             | UUID v4 |

### Endpoint Inventory

| Method | Path                              | Auth     | Idempotent | Paginated | Description                        |
|--------|-----------------------------------|----------|------------|-----------|-------------------------------------|
| GET    | /v1/users                         | Required | Yes        | Cursor    | List users                          |
| POST   | /v1/users                         | Required | No*        | --        | Create user (*use Idempotency-Key)  |
| GET    | /v1/users/{userId}                | Required | Yes        | --        | Get user by ID                      |
| PATCH  | /v1/users/{userId}                | Required | No*        | --        | Partial update (*use Idempotency-Key)|
| DELETE | /v1/users/{userId}                | Required | Yes        | --        | Soft delete user                    |

### Status Code Matrix

| Scenario                    | Status | Headers to Include           |
|-----------------------------|--------|------------------------------|
| Resource created            | 201    | Location, ETag               |
| Async job accepted          | 202    | Location (job URL)           |
| Successful delete           | 204    | --                           |
| Validation failure          | 422    | --                           |
| Auth token missing/invalid  | 401    | WWW-Authenticate             |
| Valid token, no permission  | 403    | --                           |
| Rate limit exceeded         | 429    | Retry-After, X-RateLimit-*   |

### Versioning Decision
[Version strategy with rationale based on API's consumer profile]

### Authentication Strategy
[OAuth flow selection with scope definition]

### Pagination Strategy
[Cursor or offset with rationale and parameter names]

### Caching Strategy
[Cache-Control directives per resource type]

### Error Response Contract
[RFC 7807 schema with domain-specific error codes]

### OpenAPI Spec Skeleton
[YAML skeleton with paths, schemas, and security definitions]

### Identified Issues and Recommendations
[Numbered list of specific problems found, each with a concrete fix]

Rules

  1. Never use verbs in resource URL paths for CRUD operations. POST /createUser and GET /getOrderById are wrong. The HTTP method IS the verb. Exceptions are narrow and must be sub-resource actions (POST /orders/{id}/cancel) where no clean resource noun exists.
  1. Never return 200 with an error payload. Patterns like { "success": false, "error": "not found" } with status 200 break every HTTP client, proxy, monitoring tool, and CDN. Status codes are part of the API contract and must be correct.
  1. Never expose database internals in the API. This includes: sequential integer IDs (enumeration attacks), database error messages in error responses (information leakage), column names as field names without deliberate review, and database-specific types like PostgreSQL JSONB annotations.
  1. Always version from v1 on the first external consumer. There is no such thing as an unversioned public API -- you have a v1 whether you label it or not. Adding versioning retroactively after clients exist is a breaking change.
  1. Never silently truncate or ignore invalid input. If a client sends an unknown query parameter, an extra body field, or an out-of-range value, either return a 400 validation error (strict mode) or document explicitly that extra fields are ignored (lenient mode). Choose one mode and apply it consistently.
  1. Always return consistent pagination envelope structure. Mix of paginated and non-paginated collection responses, or pagination metadata in inconsistent locations (sometimes in body, sometimes in headers), breaks client SDKs. Define one pagination contract and apply it to every collection endpoint.
  1. Never use HTTP headers to carry domain data. Request routing headers (X-Forwarded-For), tracing headers (X-Request-ID, X-Trace-ID), and caching directives belong in headers. Business data (user preferences, filter criteria, resource fields) belongs in the request body or query string. Clients cannot easily log, debug, or replay requests where data is in custom headers.
  1. Always document the 429 and 503 retry contract explicitly. Every API will rate-limit and occasionally go down. If the retry behavior is not documented and the Retry-After header is not set, clients will implement exponential backoff guesswork, hammering the API when it comes back up and causing cascading failures.
  1. Never treat PATCH as a synonym for PUT. PATCH with missing fields should update only those fields; PUT with missing fields should null them out (or return 400 if they are required). Mixing these semantics breaks clients that expect either contract.
  1. Always include Content-Type: application/json and validate it on input. Reject requests with Content-Type: application/x-www-form-urlencoded or text/plain when JSON is expected. Return 415 Unsupported Media Type. This prevents a class of security vulnerabilities including CSRF via form submission and content-type confusion attacks.
  1. Never let collection endpoints return unbounded results. Even if a collection has only 50 records today, enforce a maximum pageSize (100 is typical) and a default (20 is typical) from day one. A query that worked against 50 records will catastrophically fail against 5 million.
  1. Always propagate and log a correlation ID. Accept X-Request-ID or X-Correlation-ID from clients. If absent, generate one. Echo it in every response. Include it in every log line, every downstream service call, and every error response body. Without this, debugging production incidents across a microservices architecture is nearly impossible.

Edge Cases

Legacy Client Compatibility During Version Migration

When deprecating v1 in favor of v2, some clients (especially mobile apps that cannot be force-updated) will continue sending v1 requests for 12-18 months.

Bulk Operations and Batch Endpoints

Individual-resource endpoints at scale create N+1 HTTP request patterns. When clients need to create or update hundreds of records, individual POST calls are impractical.

Optimistic Concurrency and Conflict Handling

Without concurrency control, two clients updating the same resource simultaneously will silently overwrite each other's changes (the "lost update" problem).

Content Negotiation and Internationalization

High-Throughput Write Endpoints

Some write endpoints receive traffic spikes (e-commerce checkout, ticket sales, flash sales) that exceed direct database write capacity.

API Consumers with Inconsistent HTTP Client Implementations

Mobile apps (especially older iOS and Android versions), some server-side HTTP clients, and certain corporate proxies exhibit non-standard HTTP behavior.

Database Schema Evolution Without API Breaking Changes

The API contract and the database schema evolve independently. Changes to one must not force changes to the other.


Example

Input: "I'm building a REST API for an e-commerce platform. We have a Node.js backend (Express), PostgreSQL database, and Redis cache. The API will serve both a web frontend and a mobile app. We expect around 500 requests/second at peak. We have a team of 4 engineers. What does a production-ready implementation look like?"


Output:

REST API Design Review: E-Commerce Platform API

Resource Model

| Resource | URL Pattern | Parent | ID Type | Notes |

|------------------|-----------------------------------------------|----------|----------|--------------------------------------------|

| Users | /v1/users | -- | UUID v4 | Customers and admins via role field |

| Products | /v1/products | -- | UUID v4 | Public read, admin write |

| Categories | /v1/categories | -- | UUID v4 | Hierarchical via parentCategoryId |

| Carts | /v1/carts/{cartId} | -- | UUID v4 | Anonymous and authenticated carts |

| Cart Items | /v1/carts/{cartId}/items | Cart | UUID v4 | Items exist only within a cart |

| Orders | /v1/orders | -- | UUID v4 | Created from cart checkout |

| Order Items | /v1/orders/{orderId}/items | Order | UUID v4 | Immutable after order creation |

| Payments | /v1/payments | -- | UUID v4 | One-to-one with orders |

| Shipments | /v1/shipments | -- | UUID v4 | Linked to orders via orderId |

Products and Categories are NOT nested under each other even though a product belongs to a category -- they both have independent existence and are linked via a foreign key, not a URL hierarchy.


Endpoint Inventory

| Method | Path | Scopes Required | Idempotent | Paginated | Status Codes |

|--------|-----------------------------------|-----------------------|------------|-----------|-----------------------|

| GET | /v1/products | public | Yes | Cursor | 200, 400 |

| POST | /v1/products | products:write | No* | -- | 201, 400, 401, 403, 422 |

| GET | /v1/products/{productId} | public | Yes | -- | 200, 404 |

| PATCH | /v1/products/{productId} | products:write | No* | -- | 200, 400, 401, 403, 404, 409, 412, 422 |

| DELETE | /v1/products/{productId} | products:write | Yes | -- | 204, 401, 403, 404 |

| POST | /v1/carts | public | Yes* | -- | 201, 422 |

| POST | /v1/carts/{cartId}/items | cart:write | No* | -- | 201, 400, 404, 422 |

| DELETE | /v1/carts/{cartId}/items/{itemId} | cart:write | Yes | -- | 204, 404 |

| POST | /v1/orders | orders:write | No* | -- | 202, 400, 409, 422 |

| GET | /v1/orders/{orderId} | orders:read | Yes | -- | 200, 401, 403, 404 |

| POST | /v1/orders/{orderId}/cancel | orders:write | Yes* | -- | 200, 401, 403, 404, 409 |

| POST | /v1/payments | payments:write | No* | -- | 202, 400, 422 |

| GET | /v1/jobs/{jobId} | -- (token in URL) | Yes | -- | 200, 404 |

\* Use Idempotency-Key header.


Status Code Matrix

| Scenario | Status | Required Headers |

|--------------------------------------------|--------|-----------------------------------------------|

| Product created | 201 | Location: /v1/products/{id}, ETag: "v1" |

| Order checkout initiated (async) | 202 | Location: /v1/jobs/{jobId} |

| Cart item deleted | 204 | -- |

| Unknown productId in PATCH | 404 | -- |

| Order cancel on already-shipped order | 409 | Current order state in response body |

| PATCH with stale ETag | 412 | ETag of current version |

| Validation error on product creation | 422 | -- |

| Invalid JWT | 401 | WWW-Authenticate: Bearer error="invalid_token" |

| Valid JWT, missing products:write scope | 403 | -- |

| Rate limit hit | 429 | Retry-After: 30, X-RateLimit-Limit: 1000, X-RateLimit-Remaining: 0, X-RateLimit-Reset: 1715000400 |


Versioning Decision

Strategy: URL path versioning (/v1/).

Rationale: The API serves a mobile app that cannot be force-updated on day one. URL versioning is visible in server logs and easily routed at the API gateway (Nginx/AWS API Gateway) without needing header inspection. Mobile clients on v1 will coexist with web clients on v2 during a transition window. Register all endpoints under /v1/ from the start even if there is no v2 planned -- retrofitting the version prefix later is a breaking change.

Deprecation process: When v2 ships, add Deprecation: true and Sunset: 2026-01-01 headers to all v1 responses. Track v1 usage by client version using the User-Agent header in Datadog dashboards. Decommission v1 only when v1 traffic drops below 1% of total traffic AND mobile app store analytics show less than 1% of active users on a version that cannot upgrade.


Authentication Strategy

Web frontend: OAuth 2.0 Authorization Code flow with PKCE. Access token TTL: 15 minutes. Refresh token TTL: 30 days (sliding). Store access token in memory (not localStorage). Store refresh token in an httpOnly, Secure, SameSite=Strict cookie.

Mobile app: OAuth 2.0 Authorization Code flow with PKCE. Access token TTL: 15 minutes. Refresh token TTL: 90 days (sliding). Store both tokens in the platform secure keychain (iOS Keychain, Android Keystore).

Admin service-to-service: OAuth 2.0 Client Credentials flow. Access token TTL: 15 minutes. No refresh token -- re-authenticate on expiry.

JWT validation middleware (Express):

import { createRemoteJWKSet, jwtVerify } from 'jose';

const JWKS = createRemoteJWKSet(
  new URL('https://auth.example.com/.well-known/jwks.json'),
  { cacheMaxAge: 3_600_000 } // 1 hour TTL
);

export async function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({
      type: 'https://api.example.com/errors/unauthorized',
      title: 'Authentication Required',
      status: 401,
      detail: 'Bearer token is missing or malformed.',
      traceId: req.traceId,
    });
  }

  try {
    const { payload } = await jwtVerify(authHeader.slice(7), JWKS, {
      issuer: 'https://auth.example.com',
      audience: 'https://api.example.com',
    });
    req.user = payload;
    next();
  } catch (err) {
    return res.status(401).json({
      type: 'https://api.example.com/errors/unauthorized',
      title: 'Invalid Token',
      status: 401,
      detail: 'The provided token is expired, revoked, or has an invalid signature.',
      traceId: req.traceId,
    });
  }
}

export function requireScope(...scopes) {
  return (req, res, next) => {
    const tokenScopes = (req.user.scope || '').split(' ');
    const hasAll = scopes.every(s => tokenScopes.includes(s));
    if (!hasAll) {
      return res.status(403).json({
        type: 'https://api.example.com/errors/forbidden',
        title: 'Insufficient Scope',
        status: 403,
        detail: `This endpoint requires the following scopes: ${scopes.join(', ')}`,
        traceId: req.traceId,
      });
    }
    next();
  };
}

Pagination Strategy

Cursor-based pagination for all collection endpoints.

Rationale: Products and orders are updated frequently. Offset pagination drifts when records are inserted mid-pagination (a customer gets the same product twice or misses one). At 500 req/s, OFFSET 5000 on the products table will cause noticeable query latency as the table grows. Cursor pagination uses an index seek instead of a full scan.

Cursor encoding:

The cursor encodes the last-seen createdAt timestamp and id (for tie-breaking). It is base64url-encoded JSON, opaque to the client.

// Encode cursor
const cursor = Buffer.from(JSON.stringify({
  createdAt: lastItem.createdAt,
  id: lastItem.id,
})).toString('base64url');

// Decode cursor
const { createdAt, id } = JSON.parse(Buffer.from(cursor, 'base64url').toString());

Query pattern (PostgreSQL):

SELECT * FROM products
WHERE
  (created_at, id) < (:cursorCreatedAt, :cursorId)
  AND deleted_at IS NULL
ORDER BY created_at DESC, id DESC
LIMIT :limit + 1;  -- fetch one extra to determine if nextCursor exists

Response envelope:

{
  "data": [ /* array of product objects */ ],
  "pagination": {
    "nextCursor": "eyJjcmVhdGVkQXQiOiIyMDI0LTAzLTE1VDEwOjMwOjAwWiIsImlkIjoiMDE4ZTQ1YTItN2IzYy03ZThlLWI4MzMtMzE0ZWI3NzllMDJjIn0",
    "prevCursor": null,
    "limit": 20,
    "hasMore": true
  }
}

Caching Strategy

| Resource Type | Cache-Control Directive | ETag Strategy |

|-----------------------|------------------------------------------------------------|----------------------------------|

| Product detail (GET) | public, max-age=60, stale-while-revalidate=300 | Hash of product fields |

| Product list (GET) | public, max-age=30, stale-while-revalidate=60 | Hash of result set |

| Order detail (GET) | private, max-age=0, must-revalidate | Version counter |

| Cart detail (GET) | private, max-age=0, must-revalidate | Hash of cart contents |

| Payment detail (GET) | private, no-store | None |

| User profile (GET) | private, max-age=60, must-revalidate | Hash of user fields |

Redis cache strategy for product reads: cache product JSON at key product:{uuid} with 5-minute TTL. On PATCH/DELETE, invalidate the key synchronously before returning the response. Use Redis pipeline for batch invalidation on bulk updates.


Error Response Contract

All errors follow RFC 7807. Machine-readable error codes follow the pattern RESOURCE_REASON:

{
  "type": "https://api.example.com/errors/validation-failed",
  "title": "Request Validation Failed",
  "status": 422,
  "detail": "2 validation errors prevented the product from being created.",
  "instance": "/v1/products",
  "errors": [
    {
      "field": "price",
      "code": "PRODUCT_PRICE_NEGATIVE",
      "message": "Price must be a positive integer in cents (e.g., 1999 for $19.99)."
    },
    {
      "field": "sku",
      "code": "PRODUCT_SKU_DUPLICATE",
      "message": "A product with SKU 'WIDGET-42' already exists."
    }
  ],
  "traceId": "01HX4T2Z3M8K9P1Q"
}

Error code registry (maintain this in a shared constants file):

| Code | Status | Scenario |

|----------------------------|--------|-------------------------------------------------|

| PRODUCT_NOT_FOUND | 404 | Product ID does not exist or is deleted |

| PRODUCT_PRICE_NEGATIVE | 422 | Price field is zero or negative |

| PRODUCT_SKU_DUPLICATE | 409 | SKU already exists in the catalog |

| ORDER_INVALID_STATE | 409 | Cancellation attempted on shipped order |

| CART_ITEM_OUT_OF_STOCK | 422 | Product has insufficient inventory |

| PAYMENT_ALREADY_CAPTURED | 409 | Duplicate payment attempt detected |

| RATE_LIMIT_EXCEEDED | 429 | Too many requests |

| IDEMPOTENCY_CONFLICT | 409 | Duplicate Idempotency-Key with different body |


OpenAPI Spec Skeleton

openapi: "3.1.0"
info:
  title: E-Commerce Platform API
  version: "1.0.0"
  description: >
    Production API for the e-commerce web and mobile clients.
    All timestamps are ISO 8601 UTC. All monetary values are integers in cents.

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

security:
  - bearerAuth: []

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  schemas:
    Product:
      type: object
      required: [id, sku, name, priceInCents, currency, categoryId, createdAt, updatedAt]
      properties:
        id:
          type: string
          format: uuid
        sku:
          type: string
          maxLength: 64
        name:
          type: string
          maxLength: 255
        priceInCents:
          type: integer
          minimum: 1
          description: Price in the smallest currency unit (e.g., 1999 = $19.99)
        currency:
          type: string
          pattern: "^[A-Z]{3}$"
          description: ISO 4217 currency code
        categoryId:
          type: string
          format: uuid
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time

    ProblemDetail:
      type: object
      required: [type, title, status, traceId]
      properties:
        type:
          type: string
          format: uri
        title:
          type: string
        status:
          type: integer
        detail:
          type: string
        instance:
          type: string
        errors:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
              code:
                type: string
              message:
                type: string
        traceId:
          type: string

    CursorPagination:
      type: object
      properties:
        nextCursor:
          type: string
          nullable: true
        prevCursor:
          type: string
          nullable: true
        limit:
          type: integer
        hasMore:
          type: boolean

  parameters:
    ProductId:
      name: productId
      in: path
      required: true
      schema:
        type: string
        format: uuid
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema:
        type: string
        maxLength: 255

paths:
  /products:
    get:
      operationId: listProducts
      summary: List products
      tags: [Products]
      security: []
      parameters:
        - name: cursor
          in: query
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - name: categoryId
          in: query
          schema:
            type: string
            format: uuid
        - name: sort
          in: query
          schema:
            type: string
            enum: [createdAt:desc, createdAt:asc, price:desc, price:asc, name:asc]
            default: createdAt:desc
      responses:
        "200":
          description: Paginated product list
          headers:
            ETag:
              schema:
                type: string
            Link:
              schema:
                type: string
              description: RFC 5988 pagination links
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: "#/components/schemas/Product"
                  pagination:
                    $ref: "#/components/schemas/CursorPagination"
        "400":
          description: Invalid query parameters
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetail"

    post:
      operationId: createProduct
      summary: Create a product
      tags: [Products]
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [sku, name, priceInCents, currency, categoryId]
              properties:
                sku:
                  type: string
                  maxLength: 64
                name:
                  type: string
                  maxLength: 255
                priceInCents:
                  type: integer
                  minimum: 1
                currency:
                  type: string
                  pattern: "^[A-Z]{3}$"
                categoryId:
                  type: string
                  format: uuid
      responses:
        "201":
          description: Product created
          headers:
            Location:
              schema:
                type: string
            ETag:
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Product"
        "422":
          description: Validation failed
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/ProblemDetail"

Identified Issues and Recommendations

For a new implementation, apply these patterns from day one:

  1. **
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.