7.20. API Documentation
Table of Contents
Why API Documentation Matters
When you build a backend, you are not just writing code, you are creating a product that other developers will use. That product is your API.
Good API documentation:
- Shows what endpoints exist
- Describes how to call them
- Explains what you get back
- Clarifies errors and edge cases
Without documentation, your API is guesswork. Even if you are the only user today, future you will appreciate clear docs.
Rule: Every public API endpoint should be documented in a consistent, structured way.
Think of documentation as a contract between your backend and its consumers.
What Should Be Documented?
Documenting Endpoints
Each endpoint should have at least:
- Path:
/users,/users/{id},/login - HTTP method:
GET,POST,PUT,PATCH,DELETE - Short description: A one line summary
- Detailed description: Optional, for extra behavior and notes
Example structure:
| Field | Example |
|---|---|
| Path | /api/v1/users/{user_id} |
| Method | GET |
| Summary | Get details of a single user |
| Description | Returns public profile data for user |
You do not need to explain HTTP itself here, that belongs to other chapters. Focus on what is unique for this endpoint.
Documenting Parameters
You should clearly list and describe all parameters:
- Path parameters: Part of the URL, like
/users/{id} - Query parameters: After the
?in the URL, like/users?page=2&limit=20 - Headers: Such as
Authorization: Bearer <token> - Body fields: Data sent in
POST,PUT,PATCHrequests
Example parameter table:
| Name | In | Type | Required | Description | Example |
|---|---|---|---|---|---|
user_id | path | string | yes | Unique identifier of the user | "u_123" |
page | query | integer | no | Page number for pagination | 1 |
limit | query | integer | no | Number of items per page | 20 |
X-Trace | header | string | no | Client generated trace identifier | "req-abc-123" |
Rule: Always mark which parameters are required and which are optional.
Documenting Request Bodies
For requests with a body, document:
- Format: usually JSON
- Fields, types, and constraints
- Which fields are required
- Example body
Example for a POST /users request:
{
"email": "user@example.com",
"password": "VerySecret123",
"full_name": "Ada Lovelace"
}Example request body table:
| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
email | string | yes | Valid email format | User email |
password | string | yes | At least 8 chars, 1 number, 1 uppercase | Login password |
full_name | string | no | Max 100 characters | User full name |
Documenting Responses
Each endpoint can have multiple possible responses. At minimum, document:
- Status codes:
200 OK,201 Created,400 Bad Request, etc. - Response body schema: What JSON fields are returned
- Examples: Concrete JSON examples
Example response documentation:
| Status | Meaning | When returned |
|---|---|---|
| 200 | OK | User exists and is returned |
| 404 | Not Found | No user with given user_id |
| 401 | Unauthorized | Missing or invalid authentication |
Example success body:
{
"id": "u_123",
"email": "user@example.com",
"full_name": "Ada Lovelace",
"created_at": "2026-01-01T12:00:00Z"
}Example error body:
{
"detail": "User not found"
}Rule: Use a consistent error response format for all endpoints and document it once, then reference it everywhere.
Documenting Authentication and Authorization
Many endpoints need authentication and specific permissions. For each secured endpoint, specify:
- Whether authentication is required
- What type of authentication (for example bearer token, API key)
- Required roles or permissions
Example:
Security
- Requires:Authorization: Bearer <access_token>header
- Roles:adminorsupport
You do not need to re explain what tokens are here, that belongs to authentication chapters. Just state what is needed.
Human Friendly vs Machine Readable Documentation
There are two main consumers of API documentation:
- Humans: Developers reading a webpage or markdown file
- Machines: Tools that generate clients, tests, or interactive docs
Good API docs usually serve both.
Human Oriented Documentation
This is what developers typically read:
- Written pages on a docs site
- README files
- Tutorials and guides
- How-to examples
Characteristics:
- More text and explanations
- Narrative style
- Examples in multiple languages
- Screenshots or diagrams
Example human friendly description:
Use this endpoint to create a new user in the system.
You must provide a unique email address.
The password must meet our password policy described here:/docs/password-policy.
Machine Readable Documentation
This is a structured description of the API that tools can understand, for example:
- OpenAPI (Swagger) JSON or YAML files
- API description schemas
Tools can use these files to:
- Generate API documentation pages
- Generate client libraries
- Validate requests and responses
- Run automated tests
In later chapters you will see how frameworks like FastAPI use OpenAPI to auto generate docs. Here you just need to know that machine readable docs come from a formal specification file.
Examples of Good Documentation
Example: Simple CRUD Endpoint Docs
Imagine a simple "Tasks" API. Here is a mini documentation set for one resource.
List Tasks
- Method:
GET - Path:
/api/v1/tasks - Summary: List tasks for the current user
Query parameters:
| Name | Type | Required | Description |
|---|---|---|---|
page | integer | no | Page number, default 1 |
limit | integer | no | Items per page, max 100 |
status | string | no | Filter by status: open, done |
Responses:
200 OK
{
"items": [
{
"id": 1,
"title": "Buy milk",
"completed": false
}
],
"page": 1,
"limit": 20,
"total": 1
}
401 Unauthorized
{
"detail": "Not authenticated"
}Notice:
- Clear description
- Parameters listed
- Pagination format documented
- Two response examples
Create Task
- Method:
POST - Path:
/api/v1/tasks - Summary: Create a new task for the current user
Request body:
{
"title": "Buy milk",
"description": "2 liters of milk",
"due_date": "2026-02-01"
}| Field | Type | Required | Description |
|---|---|---|---|
title | string | yes | Short title of the task |
description | string | no | Longer description |
due_date | date | no | Due date in YYYY-MM-DD |
Responses:
201 Created
{
"id": 42,
"title": "Buy milk",
"description": "2 liters of milk",
"due_date": "2026-02-01",
"completed": false,
"created_at": "2026-01-01T09:00:00Z"
}
400 Bad Request
{
"detail": "title is required"
}This is enough for another developer to start using the API immediately.
Consistency and Versioning in Documentation
Keep Documentation in Sync With Code
One of the hardest parts of API documentation is keeping it up to date. Out of date docs are worse than no docs, because they mislead developers.
Rule: When you change an API endpoint, update the documentation in the same pull request.
Common practices:
- Store API docs in the same repository as the backend code
- Review documentation changes in code reviews
- Use automatic generators where possible to reduce manual work
You will learn about OpenAPI / Swagger in another chapter, which helps generate docs from code.
Document Versions of Your API
When you change your API in a way that breaks existing clients, you usually create a new version. You should:
- Show the version in the URL or headers (covered elsewhere)
- Provide separate documentation for each version
Example URLs for docs:
/docs/v1//docs/v2/
Example statement in documentation:
This page documentsv2of the API. Forv1, see/docs/v1/tasks.
If you remove or change an endpoint, mention:
- From which version it is available
- Until which version it is supported
Example:
DELETE /tasks/{id}is available starting fromv2.
Inv1, tasks can only be marked as completed, not deleted.
Practical Tips for Writing API Documentation
Use a Standard Layout for Endpoints
Pick a structure and reuse it for every endpoint. For example always use this order:
- Summary
- Method and path
- Authentication
- Parameters
- Request body
- Responses
- Examples
- Notes
Example template:
### Summary
Short sentence.
### Method and path
`GET /api/v1/resource/{id}`
### Authentication
Required: Yes / No
Type: ...
### Parameters
| Name | In | Type | Required | Description |
|------|----|------|----------|-------------|
| ... | | | | |
### Request body
Format: JSON
Schema:
...
Example:
...
### Responses
`200 OK`
Example:
...
`4xx / 5xx` errors:
...
### Notes
- Any special behavior or limitationsYou can copy this template for your own projects.
Provide Example Requests and Responses
Examples are the most helpful part of API docs. Include:
- At least one success example
- At least one error example
- Curl or HTTPie examples
Example curl:
curl -X POST https://api.example.com/api/v1/tasks \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-token>" \
-d '{
"title": "Buy milk",
"description": "2 liters of milk"
}'Example HTTPie:
http POST https://api.example.com/api/v1/tasks \
Authorization:"Bearer <your-token>" \
title="Buy milk" \
description="2 liters of milk"Document Common Patterns Once
Some things apply to almost every endpoint, for example:
- Authentication headers
- Pagination format
- Error response format
- Rate limiting headers
Document these in a General or Conventions section and then link to them from each endpoint.
Example general pagination section:
All list endpoints use the same pagination format:
Request parameters:page,limit
Response fields:items,page,limit,total
Then in the endpoint docs, you can just write:
This endpoint uses standard pagination. See /docs/pagination.
Interactive API Documentation
Interactive documentation lets developers try endpoints directly in the browser.
Typical features:
- List of all endpoints in a sidebar
- Click an endpoint to see details
- Fill parameters and body
- Click "Try it out"
- See response directly
To support this, your backend exposes:
- A machine readable spec (for example OpenAPI JSON)
- A UI page that reads this spec and displays docs
In a later chapter about FastAPI you will see real examples where /docs automatically shows interactive documentation.
Benefits:
- Clients can experiment quickly
- You can verify behavior while reading docs
- Keeps docs and implementation closely synchronized
Documenting Non Functional Aspects
Apart from endpoints, it is useful to document some operational and business rules.
Rate Limits and Quotas
If your API limits how often it can be called:
- Clearly state the limit (for example requests per minute)
- Explain how the limit is enforced (per IP, per token, etc.)
- Show what error is returned when limit is exceeded
Example:
Each API key is limited to 1000 requests per hour. If you exceed this limit, you will receive a 429 Too Many Requests response:
{
"detail": "Rate limit exceeded, try again in 120 seconds"
}Business Rules and Constraints
Some constraints are not obvious from types alone. For example:
- Maximum number of tasks per user
- Which fields must be unique
- Allowed transitions for a status field
Example documentation:
A user can have at most 500 active tasks.
Thestatusfield can only change in this order:
-opentoin_progress
-in_progresstodone
Once a task isdone, it cannot go back toopenorin_progress.
Deprecations
When you plan to remove something:
- Mark endpoints or fields as deprecated
- Suggest alternatives
- Provide a timeline
Example:
GET /api/v1/tasks/allis deprecated and will be removed on 2027-01-01.
UseGET /api/v1/taskswith filters instead.
Summary
In this chapter you learned what makes API documentation useful:
- Document every endpoint with method, path, parameters, body, and responses
- Show clear examples for both success and error cases
- Keep docs in sync with code and version them alongside the API
- Use consistent layouts and shared conventions
- Provide both human friendly text and machine readable specs
- Clearly state authentication, rate limits, and business rules
Later, when you use tools like OpenAPI and FastAPI, you will see how a lot of this documentation can be generated automatically if you design your API carefully.
Views: 7
KAHIBARO