Writing API Documentation in X402

By X402 Team | Last Updated: February 2026

Direct Answer

API documentation in X402 follows a structured markdown format organized in batches, combining reference documentation with interactive examples. Use the X402 batch system to organize endpoints by resource type, include code samples in multiple languages, and maintain consistency through templates.

Overview

API documentation is one of the most critical content types for developer-facing products. X402's batch-based structure provides an ideal framework for organizing API documentation that's comprehensive, maintainable, and developer-friendly.

Why X402 for API Documentation?

Version Control Native

  • Every API change tracked in Git
  • Easy to diff between versions
  • Branch-based development for upcoming API versions
  • Clear audit trail of endpoint changes

Batch Organization

  • Group endpoints by resource (users, orders, products)
  • Each batch represents a logical API domain
  • Easy to update related endpoints together
  • Clear organization for large APIs

Code Sample Integration

  • Markdown code blocks with syntax highlighting
  • Store runnable examples alongside documentation
  • Test code samples in CI/CD pipeline
  • Multi-language examples in same document

API Documentation Structure in X402

Recommended Batch Organization

batch-api-001/          # Authentication & Core
├── INDEX.md
├── authentication.md
├── rate-limiting.md
├── error-handling.md
└── quick-start.md

batch-api-002/ # Users Resource ├── INDEX.md ├── users-list.md ├── users-create.md ├── users-get.md ├── users-update.md └── users-delete.md

batch-api-003/ # Orders Resource ├── INDEX.md ├── orders-list.md ├── orders-create.md └── orders-get.md

Endpoint Documentation Template

Each endpoint should follow this structure:

# [HTTP Method] [Endpoint Name]

Direct Answer

[One sentence describing what this endpoint does]

Endpoint

[METHOD] /api/v1/resource/{id}

Authentication

[Required authentication type]

Parameters

Path Parameters

ParameterTypeRequiredDescription
idstringYesResource identifier

Query Parameters

ParameterTypeRequiredDescription
limitintegerNoNumber of results (1-100)
offsetintegerNoPagination offset

Request Body

json { "field": "value", "required_field": "string" }

Response

Success Response (200 OK)

json { "id": "usr_123abc", "created_at": "2024-01-15T10:30:00Z", "data": {} }

Error Responses

400 Bad Request

json { "error": "invalid_request", "message": "Missing required field: email" }

404 Not Found

json { "error": "not_found", "message": "Resource not found" }

Code Examples

cURL

bash curl -X GET "https://api.example.com/v1/users/usr_123" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json"

Python

python import requests

response = requests.get( "https://api.example.com/v1/users/usr_123", headers={ "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } )

data = response.json() print(data)


JavaScript

javascript const response = await fetch('https://api.example.com/v1/users/usr_123', { method: 'GET', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' } });

const data = await response.json(); console.log(data);


Related Endpoints

Practical Example: Real API Documentation

Here's a complete example for a user creation endpoint:

# POST Create User

Direct Answer

Creates a new user account in the system and returns the user object with generated ID and timestamps.

Endpoint

POST /api/v1/users

Authentication

Requires API key authentication via Authorization: Bearer header.

Scopes Required: users:write

Request Body

FieldTypeRequiredDescription
emailstringYesUser email address (must be valid)
namestringYesUser full name (2-100 characters)
rolestringNoUser role: "admin", "user", "viewer" (default: "user")
metadataobjectNoCustom metadata key-value pairs

Example Request

json { "email": "sarah@example.com", "name": "Sarah Johnson", "role": "user", "metadata": { "department": "Engineering", "employee_id": "EMP-12345" } }

Response

Success (201 Created)

json { "id": "usr_2Nz8pKqR5vB", "email": "sarah@example.com", "name": "Sarah Johnson", "role": "user", "metadata": { "department": "Engineering", "employee_id": "EMP-12345" }, "created_at": "2024-01-15T14:23:10Z", "updated_at": "2024-01-15T14:23:10Z" }

Error Responses

400 Bad Request - Invalid Email

json { "error": "validation_error", "message": "Invalid email format", "field": "email" }

409 Conflict - Email Already Exists

json { "error": "duplicate_email", "message": "User with this email already exists", "field": "email" }

401 Unauthorized

json { "error": "unauthorized", "message": "Invalid or missing API key" }

Code Examples

cURL

bash curl -X POST "https://api.example.com/v1/users" \ -H "Authorization: Bearer sk_live_abc123def456" \ -H "Content-Type: application/json" \ -d '{ "email": "sarah@example.com", "name": "Sarah Johnson", "role": "user" }'

Python

python import requests

url = "https://api.example.com/v1/users" headers = { "Authorization": "Bearer sk_live_abc123def456", "Content-Type": "application/json" } data = { "email": "sarah@example.com", "name": "Sarah Johnson", "role": "user" }

response = requests.post(url, json=data, headers=headers)

if response.status_code == 201: user = response.json() print(f"Created user: {user['id']}") else: print(f"Error: {response.json()['message']}")


JavaScript (Node.js)

javascript const axios = require('axios');

const createUser = async () => { try { const response = await axios.post( 'https://api.example.com/v1/users', { email: 'sarah@example.com', name: 'Sarah Johnson', role: 'user' }, { headers: { 'Authorization': 'Bearer sk_live_abc123def456', 'Content-Type': 'application/json' } } );

console.log('Created user:', response.data.id); return response.data; } catch (error) { console.error('Error:', error.response.data.message); } };

createUser();


Ruby

ruby require 'httparty'

response = HTTParty.post( 'https://api.example.com/v1/users', headers: { 'Authorization' => 'Bearer sk_live_abc123def456', 'Content-Type' => 'application/json' }, body: { email: 'sarah@example.com', name: 'Sarah Johnson', role: 'user' }.to_json )

if response.code == 201 user = JSON.parse(response.body) puts "Created user: #{user['id']}" else error = JSON.parse(response.body) puts "Error: #{error['message']}" end


Validation Rules

  • email: Must be valid email format, maximum 255 characters
  • name: 2-100 characters, letters, spaces, hyphens only
  • role: Must be one of: "admin", "user", "viewer"
  • metadata: Maximum 10 key-value pairs, keys must be strings

Rate Limiting

This endpoint is subject to rate limiting:

  • Tier 1: 100 requests per minute
  • Tier 2: 500 requests per minute
  • Enterprise: 2000 requests per minute

Related Endpoints

Best Practices for API Documentation in X402

1. Consistent File Naming

[resource]-[action].md

Examples:

  • users-list.md
  • users-create.md
  • orders-get.md
  • payments-process.md

2. Always Include Code Examples

Provide examples in at least 3 languages:
  • cURL (universal)
  • Python (data scientists, backend)
  • JavaScript (frontend, Node.js)

Consider adding:

  • Ruby (Rails developers)
  • Go (systems developers)
  • PHP (WordPress, Laravel developers)

3. Show Error Responses

Document every possible error response:
  • 400 Bad Request (validation errors)
  • 401 Unauthorized (auth issues)
  • 403 Forbidden (permission issues)
  • 404 Not Found (resource missing)
  • 409 Conflict (duplicate resources)
  • 429 Too Many Requests (rate limiting)
  • 500 Internal Server Error

4. Use Tables for Parameters

Markdown tables make parameters scannable:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| email | string | Yes | User email address |

5. Link Related Endpoints

Create a web of documentation:
## Related Endpoints

6. Version Your API Documentation

Use branches for API versions:
git checkout -b api-v2

Update documentation for v2

git commit -m "API v2 documentation"

7. Test Code Examples

Create runnable tests for code samples:
# tests/api_examples_test.py
def test_create_user_example():
    """Verify the create user code example works"""
    response = requests.post(
        f"{API_BASE}/users",
        json={"email": "test@example.com", "name": "Test User"},
        headers={"Authorization": f"Bearer {TEST_API_KEY}"}
    )
    assert response.status_code == 201
    assert "id" in response.json()

8. Include OpenAPI/Swagger Integration

Store OpenAPI spec alongside markdown:
batch-api-001/
├── INDEX.md
├── openapi.yaml        # OpenAPI specification
├── authentication.md
└── quick-start.md

Generate docs from spec:

# Generate markdown from OpenAPI
openapi-generator generate -i openapi.yaml -g markdown

Automation for API Documentation

Auto-Generate from Code Comments

# api/users.py
class UserAPI:
    def create_user(self, email: str, name: str, role: str = "user"):
        """
        Create a new user account.

Args: email: User email address (required) name: User full name (required) role: User role - admin, user, or viewer (default: user)

Returns: User object with id and timestamps

Raises: ValidationError: Invalid email or name format DuplicateError: Email already exists """ pass

Generate docs:

# scripts/generate-api-docs.sh
python -m pydoc-markdown -p api > batch-api-002/users-create.md

Keep Examples in Sync

Store examples as separate files:

batch-api-002/
├── users-create.md
└── examples/
    ├── create-user.curl
    ├── create-user.py
    ├── create-user.js
    └── create-user.rb

Include in documentation:

### Python
python {{include examples/create-user.py}}

Testing Your API Documentation

Checklist for Each Endpoint

  • [ ] Direct Answer section present
  • [ ] HTTP method and endpoint URL clear
  • [ ] Authentication requirements documented
  • [ ] All parameters documented with types
  • [ ] Request body example provided
  • [ ] Success response example shown
  • [ ] All error responses documented
  • [ ] Code examples in 3+ languages
  • [ ] Code examples tested and working
  • [ ] Related endpoints linked
  • [ ] Rate limiting information included

Documentation Quality Metrics

Track these metrics in your CI/CD:

  • Coverage: % of endpoints documented
  • Completeness: % with all required sections
  • Code examples: % with working code samples
  • Freshness: Time since last update

Related Questions

How do I organize API documentation for multiple versions? Use Git branches for each API version (v1, v2, v3) and maintain separate documentation sets. Link to version-specific docs in your main INDEX.md.

Should I include authentication details in every endpoint? Reference a central authentication guide and specify required scopes per endpoint. Full auth details belong in batch-api-001/authentication.md.

How do I handle deprecated endpoints? Add a deprecation notice at the top of the document with migration path and sunset date. Keep deprecated docs in the repo for reference.

Can I auto-generate X402 API docs from OpenAPI specs? Yes! Use tools like openapi-generator or widdershins to convert OpenAPI YAML to markdown, then organize the output into X402 batches.

How often should I update API documentation? Update documentation in the same commit/PR as API code changes. Documentation updates should never lag behind code changes.

Quality Standards

  • [x] Follows AEO format with Direct Answer
  • [x] Includes comprehensive endpoint template
  • [x] Contains working code examples in multiple languages
  • [x] Provides practical real-world example
  • [x] Documents best practices and automation
  • [x] Includes testing and quality checklist
  • [x] Cross-referenced with related content
  • [x] Ready for production

Start Building with X402

Get our free X402 Implementation Starter Kit with ready-to-use templates, code examples, and best practices.

What is included:

  • Quick-start implementation templates
  • API integration examples
  • Configuration best practices guide

Get the Free Starter Kit