KAHIBARO
Discord Login Register

7.20. API Documentation

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:

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:

Example structure:

FieldExample
Path/api/v1/users/{user_id}
MethodGET
SummaryGet details of a single user
DescriptionReturns 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:

Example parameter table:

NameInTypeRequiredDescriptionExample
user_idpathstringyesUnique identifier of the user"u_123"
pagequeryintegernoPage number for pagination1
limitqueryintegernoNumber of items per page20
X-TraceheaderstringnoClient 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:

Example for a POST /users request:

json
{
  "email": "user@example.com",
  "password": "VerySecret123",
  "full_name": "Ada Lovelace"
}

Example request body table:

FieldTypeRequiredConstraintsDescription
emailstringyesValid email formatUser email
passwordstringyesAt least 8 chars, 1 number, 1 uppercaseLogin password
full_namestringnoMax 100 charactersUser full name

Documenting Responses

Each endpoint can have multiple possible responses. At minimum, document:

Example response documentation:

StatusMeaningWhen returned
200OKUser exists and is returned
404Not FoundNo user with given user_id
401UnauthorizedMissing or invalid authentication

Example success body:

json
{
  "id": "u_123",
  "email": "user@example.com",
  "full_name": "Ada Lovelace",
  "created_at": "2026-01-01T12:00:00Z"
}

Example error body:

json
{
  "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:

Example:

Security

- Requires: Authorization: Bearer <access_token> header
- Roles: admin or support

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:

  1. Humans: Developers reading a webpage or markdown file
  2. Machines: Tools that generate clients, tests, or interactive docs

Good API docs usually serve both.

Human Oriented Documentation

This is what developers typically read:

Characteristics:

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:

Tools can use these files to:

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

Query parameters:

NameTypeRequiredDescription
pageintegernoPage number, default 1
limitintegernoItems per page, max 100
statusstringnoFilter by status: open, done

Responses:

200 OK

json
{
  "items": [
    {
      "id": 1,
      "title": "Buy milk",
      "completed": false
    }
  ],
  "page": 1,
  "limit": 20,
  "total": 1
}

401 Unauthorized

json
{
  "detail": "Not authenticated"
}

Notice:

Create Task

Request body:

json
{
  "title": "Buy milk",
  "description": "2 liters of milk",
  "due_date": "2026-02-01"
}
FieldTypeRequiredDescription
titlestringyesShort title of the task
descriptionstringnoLonger description
due_datedatenoDue date in YYYY-MM-DD

Responses:

201 Created

json
{
  "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

json
{
  "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:

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:

Example URLs for docs:

Example statement in documentation:

This page documents v2 of the API. For v1, see /docs/v1/tasks.

If you remove or change an endpoint, mention:

Example:

DELETE /tasks/{id} is available starting from v2.
In v1, 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:

  1. Summary
  2. Method and path
  3. Authentication
  4. Parameters
  5. Request body
  6. Responses
  7. Examples
  8. Notes

Example template:

text
### 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 limitations

You can copy this template for your own projects.

Provide Example Requests and Responses

Examples are the most helpful part of API docs. Include:

Example curl:

bash
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:

bash
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:

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:

To support this, your backend exposes:

In a later chapter about FastAPI you will see real examples where /docs automatically shows interactive documentation.

Benefits:

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:

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:
json
{
  "detail": "Rate limit exceeded, try again in 120 seconds"
}

Business Rules and Constraints

Some constraints are not obvious from types alone. For example:

Example documentation:

A user can have at most 500 active tasks.
The status field can only change in this order:
- open to in_progress
- in_progress to done
Once a task is done, it cannot go back to open or in_progress.

Deprecations

When you plan to remove something:

Example:

GET /api/v1/tasks/all is deprecated and will be removed on 2027-01-01.
Use GET /api/v1/tasks with filters instead.

Summary

In this chapter you learned what makes API documentation useful:

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

Comments

Please login to add a comment.

Don't have an account? Register now!