Skip to content
StackPractices
beginner By Mathias Paulenko

API Documentation Template

A reusable template for documenting REST and GraphQL APIs with endpoints, schemas, errors, and examples.

Topics: api

Note: This guide follows English-language naming conventions and terminology standards common in international development teams. Examples use English identifiers and comments to maximize compatibility across codebases and tooling.

Template Structure

Use this template as the foundation for documenting any HTTP API. Replace bracketed sections with your API-specific content.


1. Overview

Base URL

https://api.example.com/v1

Authentication

All endpoints require a Bearer token in the Authorization header:

Authorization: Bearer <your_api_key>

Content-Type

Requests and responses use application/json unless specified otherwise. See Parse JSON for handling JSON payloads.

Rate Limits

  • 100 requests per minute for authenticated users
  • 10 requests per minute for anonymous users
  • Rate limit headers included in all responses:
    • X-RateLimit-Limit
    • X-RateLimit-Remaining
    • X-RateLimit-Reset

2. Endpoints

[Resource Name]

GET /[resource]

List all [resources] with optional filtering and pagination.

Query Parameters

ParameterTypeRequiredDescription
pageintegerNoPage number (default: 1)
limitintegerNoItems per page (default: 20, max: 100)
sortstringNoSort field and direction (created_at:desc)
filter[field]stringNoFilter by field value

Response 200 OK

{
  "data": [
    {
      "id": "string",
      "created_at": "2026-01-01T00:00:00Z",
      "updated_at": "2026-01-01T00:00:00Z"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 100,
    "total_pages": 5
  }
}

POST /[resource]

Create a new [resource].

Request Body

{
  "name": "string (required, max 255 chars)",
  "description": "string (optional, max 1000 chars)"
}

Response 201 Created

{
  "id": "string",
  "name": "string",
  "description": "string",
  "created_at": "2026-01-01T00:00:00Z"
}

GET /[resource]/{id}

Retrieve a single [resource] by ID.

Path Parameters

ParameterTypeRequiredDescription
idstringYesUnique resource identifier

Response 200 OK

{
  "id": "string",
  "name": "string",
  "description": "string",
  "created_at": "2026-01-01T00:00:00Z",
  "updated_at": "2026-01-01T00:00:00Z"
}

PATCH /[resource]/{id}

Partially update a [resource]. Only provided fields are modified.

Request Body

{
  "name": "string (optional)",
  "description": "string (optional)"
}

Response 200 OK

{
  "id": "string",
  "name": "string",
  "description": "string",
  "updated_at": "2026-01-01T00:00:00Z"
}

DELETE /[resource]/{id}

Delete a [resource] by ID.

Response 204 No Content


3. Error Responses

All errors follow this structure. For a dedicated error response template, see API Error Response Template. See Input Validation for request validation patterns.

{
  "error": {
    "code": "invalid_request",
    "message": "Human-readable description",
    "details": [
      {
        "field": "name",
        "issue": "is required"
      }
    ]
  }
}

Common HTTP Status Codes

StatusCodeDescription
400bad_requestMalformed request or validation error
401unauthorizedMissing or invalid authentication
403forbiddenInsufficient permissions
404not_foundResource does not exist
409conflictResource conflict (e.g., duplicate unique field)
422unprocessable_entitySemantic validation error
429rate_limitedToo many requests
500internal_errorServer-side error

4. SDKs & Tools

  • cURL: All examples use standard cURL commands
  • Postman: Import our OpenAPI spec
  • OpenAPI: Auto-generated spec available at /openapi.json

5. Changelog

VersionDateChanges
1.0.02026-06-10Initial release

Customization Guide

  1. Replace [resource] with your actual domain entity (e.g., users, orders, products)
  2. Add endpoint-specific query parameters and response fields
  3. Include authentication examples for OAuth, API keys, or JWT
  4. Add code examples in Python, JavaScript, and Java
  5. Link to your OpenAPI/Swagger spec for interactive documentation

Frequently Asked Questions

Should I document every endpoint or only public ones?

Document every endpoint that is consumed by clients, including internal microservices. Internal-only endpoints can have lighter documentation, but they should still be discoverable and understandable by other teams.

What is the difference between API documentation and an OpenAPI spec?

API documentation is the human-readable guide with explanations, examples, and context. An OpenAPI spec is the machine-readable contract that powers interactive docs, client generation, and contract testing. Maintain both.

How do I keep API docs in sync with code?

Generate documentation from code annotations or OpenAPI specs as part of your CI pipeline. Use tools like Swagger UI, Redoc, or Stoplight to render specs automatically. See REST API Design Guide for what works in API design. Manual docs drift quickly without automation.

Variant Comparison

VariantContextApproachNotes
REST with OpenAPIPublic API, external clientsOpenAPI spec + narrative docsGenerates clients automatically
GraphQL with schemaAPI with flexible queriesSchema SDL + query examplesSingle endpoint
gRPC with protoInternal microservices.proto files + generated docsBinary, high performance
Simple MarkdownSmall internal APIManual docs in repoSufficient for 2-3 endpoints

Detailed Scenario: Documenting an Order Creation Endpoint

Endpoint: POST /v1/orders
Authentication: Bearer token (JWT)
Rate limit: 100 req/min per user

Request:
  POST /v1/orders HTTP/1.1
  Host: api.example.com
  Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
  Content-Type: application/json
  Idempotency-Key: client-uuid-12345

  {
    "customer_id": "usr_abc123",
    "items": [
      {"sku": "PROD-001", "quantity": 2},
      {"sku": "PROD-002", "quantity": 1}
    ],
    "shipping_address_id": "addr_xyz789"
  }

Response 201 Created:
  HTTP/1.1 201 Created
  Content-Type: application/json
  Location: /v1/orders/ord_def456

  {
    "id": "ord_def456",
    "customer_id": "usr_abc123",
    "status": "pending",
    "items": [
      {"sku": "PROD-001", "quantity": 2, "unit_price_cents": 1999},
      {"sku": "PROD-002", "quantity": 1, "unit_price_cents": 4999}
    ],
    "total_cents": 8997,
    "currency": "USD",
    "placed_at": "2026-07-11T14:30:00Z"
  }

Key headers:
  Idempotency-Key: Prevents duplicates on client retry
  Location: URL of created resource for redirect

Possible errors:
  400 - customer_id does not exist or is inactive
  409 - Idempotency-Key already used with different body
  422 - quantity <= 0 or SKU not found

How do I document cursor-based vs offset-based pagination?

Document both if you support them. Offset-based uses page and limit (simpler, but slow on large datasets). Cursor-based uses after (an ID or opaque cursor) and limit (more efficient, no skipped records). Include examples of both in the documentation and recommend cursor-based for datasets exceeding 10,000 records.

Should I include code examples in multiple languages?

If your API has consumers in multiple languages, yes. Include examples in cURL (universal), Python (requests), and JavaScript (fetch). Keep examples short and focused on one endpoint each. For internal APIs with a single consuming language, one language is enough.