API Documentation
Document an API so a stranger can succeed on the first attempt: a contract-first reference, a tested quickstart, an error catalog, and a clear change and deprecation policy.
Introduction
For an integrating developer, the documentation is the product. They cannot ask the team, read the source, or attend a design meeting. They have a text editor, an API key, and perhaps an hour of patience.
API documentation is also the most checkable documentation: the contract can be validated, examples can be executed, and the implementation can be tested against both. This lesson uses that advantage.
The endpoints, fields, and numbers below are illustrative. Replace them with those of your own API.
Learning Objectives
- Identify what API consumers need and in what order.
- Use an API contract (OpenAPI) as the source of truth for reference documentation.
- Write reference entries that include examples, errors, and edge cases.
- Write a quickstart and guides that actually run.
- Document errors, authentication, pagination, limits, and idempotency.
- Define a change log and a deprecation policy.
- Verify that the documentation matches the implementation.
- Use AI to draft and review API documentation safely.
1. What API Consumers Need
In order of when they need it:
- What is this, and is it right for me? A short overview and a list of capabilities.
- How do I get access? Authentication and credentials, in a form they can try immediately.
- How do I make my first successful call? A quickstart that takes minutes.
- How do I do the thing I came for? Task-based guides (import feedback, list items, handle results).
- What exactly does this endpoint accept and return? Reference.
- Why did it fail, and what should I do? Error documentation.
- What will change, and when? Changelog and deprecation policy.
Most weak API documentation is only item 5. Items 3, 4, and 6 are what decide whether integration succeeds.
2. Contract First
Write or generate an OpenAPI description and treat it as the source of truth. Reference pages are generated from it, tests validate against it, and clients can be generated from it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
openapi: 3.1.0
info:
title: SignalDesk API
version: 0.1.0
description: >
Import customer feedback and retrieve it, scoped to a workspace.
paths:
/v1/workspaces/{workspace_id}/imports:
post:
operationId: createImport
summary: Start a CSV feedback import
description: >
Uploads a CSV file and starts a background import. The request
returns immediately with an import in `queued` status. Poll
the import, or subscribe to the `import.completed` webhook,
to learn the result. Rows that fail validation do not stop
the import; they are listed in the import's `rejected_rows`.
parameters:
- name: workspace_id
in: path
required: true
schema: { type: string }
description: The workspace that will own the imported feedback.
- name: Idempotency-Key
in: header
required: false
schema: { type: string, maxLength: 64 }
description: >
Repeating a request with the same key within 24 hours
returns the original import instead of creating another.
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [file]
properties:
file:
type: string
format: binary
description: A UTF-8 CSV file; see the CSV format reference.
responses:
"202":
description: Import accepted and queued.
content:
application/json:
schema: { $ref: "#/components/schemas/Import" }
example:
id: imp_01HXYZ
status: queued
total_rows: null
"400":
$ref: "#/components/responses/InvalidRequest"
"401":
$ref: "#/components/responses/Unauthorized"
"413":
$ref: "#/components/responses/FileTooLarge"
Put the explanations in the contract: descriptions, examples, constraints, and defaults. A contract without descriptions generates a reference that tells the reader only what they can already see.
Workflow options:
- Contract first: design and review the contract, then implement. Best for new APIs.
- Code first: generate the contract from annotated code. Fast, but descriptions are often thin; treat generated output as a starting point to enrich.
- Either way, the contract in the repository must be the one the tests check.
3. Writing Good Reference Entries
For each operation, a reader should find:
| Element | Notes |
|---|---|
| Purpose in one sentence | What the call does, not how it is implemented |
| Method, path, and parameters | Type, required or optional, constraints, defaults |
| Request example | Complete and realistic; copyable |
| Response example | For success and the common errors |
| Field descriptions | Meaning, units, formats (timestamps, IDs), nullability |
| Errors | Which codes can occur here and what causes them |
| Side effects | What changes; whether it is safe to repeat |
| Permissions | Which credentials or roles may call it |
| Limits | Size limits, rate limits, pagination behavior |
Common omissions: what happens when a list is empty, whether a field can be null, how timestamps are formatted and in which time zone, whether results are sorted, and what a repeated request does. These are exactly the questions asked in support.
4. Cross-Cutting Topics
Document once, in dedicated pages, and link from every endpoint:
- Authentication: how to obtain and send credentials, how they expire, how to rotate them.
- Workspaces and permissions: which resources belong to which workspace, and what a cross-workspace request returns (the quality course tested this).
- Pagination: cursor or page parameters, maximum page size, how to detect the end.
- Errors: one format for all errors (see below).
- Rate limits and quotas: the actual limits, the response when exceeded, and the headers that report remaining capacity. State a limit only if it is enforced.
- Idempotency and retries: which calls are safe to repeat and how.
- Asynchronous operations: how to poll, how long to wait, and what the statuses mean.
- Webhooks (if offered): events, payloads, signatures, retries.
- Versioning: how versions are identified and what counts as a breaking change.
5. A Quickstart That Works
A quickstart has one goal: first successful call, in minutes. It is a tutorial, so it must guarantee success.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Quickstart: import your first feedback file
You will upload a small CSV file and see the imported items.
This takes about five minutes.
## Before you begin
- A SignalDesk workspace and an API key (see Authentication).
- `curl` installed.
## 1. Create a sample file
...(the file content, complete)
## 2. Start the import
```bash
curl -X POST https://api.example.com/v1/workspaces/$WORKSPACE_ID/imports \
-H "Authorization: Bearer $SIGNALDESK_API_KEY" \
-F file=@feedback.csv
```
Expected response: status `202` and a body like ... (shown in full)
## 3. Check the result
...
## What next
Links to guides for handling rejected rows and webhooks.
Rules for examples:
- Use placeholders that are obviously fake (
$SIGNALDESK_API_KEY,example.com). - Show the expected output after each step.
- Provide examples in the languages your consumers use, and keep each one small.
- Execute every example in CI against a running test instance or a recorded server (lesson 3). An unexecuted example is a bug waiting.
6. Documenting Errors
Define one error format and a catalog that maps each code to cause and resolution.
1
2
3
4
5
6
7
8
{
"error": {
"code": "FILE_TOO_LARGE",
"message": "The file exceeds the maximum size of 10 MB.",
"request_id": "req_8f3a",
"details": { "max_bytes": 10485760 }
}
}
| Code | HTTP | Cause | What to do |
|---|---|---|---|
INVALID_REQUEST |
400 | Missing or malformed parameter | Check the field named in details. |
UNAUTHORIZED |
401 | Missing or invalid credentials | Verify the API key and its scope. |
NOT_FOUND |
404 | Resource does not exist or belongs to another workspace | Check the identifier and the workspace. |
FILE_TOO_LARGE |
413 | File exceeds the maximum size | Split the file and retry. |
RATE_LIMITED |
429 | Too many requests | Wait for Retry-After seconds. |
Generate the catalog from the error definitions in code where possible, so that a new error cannot be added without documentation. Add the human resolution column by hand. Tell readers what to do, not only what happened. Include the request_id in the format and explain how support uses it.
7. Change Log and Deprecation Policy
Consumers need to know what will break and when.
- Define “breaking”: removing or renaming a field, changing a type or meaning, tightening validation, or changing error codes can all break clients. Adding an optional field usually does not. Say what you treat as compatible.
- Publish a changelog with date, version, and category: added, changed, deprecated, removed, fixed.
- Deprecation policy: how far in advance you announce, how deprecation is signaled (a documentation note, a response header, a changelog entry), and how long the old behavior remains. Do not promise a period you will not honor.
- Migration guides for breaking changes, with before and after examples.
8. Keeping Documentation and Implementation Aligned
Close the loop with automation (building on the quality course):
| Check | How |
|---|---|
| Contract is valid and follows your rules | Lint the OpenAPI file in CI |
| Implementation matches the contract | Run contract tests: validate real responses against the schema |
| Examples are valid | Validate every example against its schema, and execute the quickstart |
| Error catalog is complete | Compare codes in code with codes documented |
| Nothing changed without notice | Diff the contract between releases and flag breaking changes |
| New endpoints are tenant-isolated and documented | A contract-derived test fails on an undocumented route |
The tenant-isolation tests from the quality course were generated from the API contract. The same contract now drives documentation, so one source of truth serves tests and readers.
9. Using AI for API Documentation
Enrich the contract from the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Act as an API documentation writer.
Inputs:
- OpenAPI file (descriptions may be missing): [paste]
- Handler code, validation rules, and error handling: [paste]
- Tests for these endpoints: [paste]
- Style guide and glossary: [paste]
Tasks:
1. For each operation and field lacking a description, draft one
based only on the code and tests. Cite the source.
2. List behaviors visible in code or tests but missing from the
contract: limits, defaults, error conditions, side effects,
idempotency.
3. List contradictions between contract, code, and tests.
4. Draft realistic examples for requests, successful responses, and
each documented error.
Use [UNKNOWN] for anything not supported by the inputs. Do not
invent limits, defaults, or behavior.
Review from the consumer’s side.
1
2
3
4
5
6
7
8
Act as a developer integrating this API for the first time, using
only this documentation.
Task: Write the code (in Python) for: authenticate, import a CSV
file, wait for completion, and list rejected rows. At every point
where the documentation is insufficient or ambiguous, stop and
list the missing information. Then list every error you would
expect to handle and whether the documentation tells you how.
Run the generated code against a test instance. Where it fails, either the documentation or the API is wrong, and both are worth fixing.
10. Practical Exercise
For SignalDesk (or your project):
- Write or complete the OpenAPI contract for the import, status, and list endpoints, with descriptions, examples, and all error responses.
- Run the contract enrichment prompt, verify each suggestion against the code, and merge the valid ones.
- Write the authentication, pagination, error, and asynchronous operation guides.
- Write the quickstart, and execute it in CI.
- Create the error catalog, generated from code, with a hand-written resolution column.
- Write the change log and the deprecation policy.
- Add the alignment checks: contract lint, response validation, and a completeness check for error codes.
- Run the “first-time integrator” prompt, execute the code it produces, and fix what fails.
- Ask someone outside the team to follow the quickstart and record where they hesitate.
Verification
You are ready to continue when:
- The contract validates, every endpoint has descriptions, examples, and errors, and tests check responses against it.
- A newcomer can complete the quickstart without help, in the time it promises.
- Every error code the system can return appears in the catalog with a resolution.
- Every example is executed or validated automatically.
- Limits and guarantees in the documentation match what is enforced.
- Breaking-change rules and deprecation timelines are written and approved by the owner.
Key Takeaways
- API consumers need a quickstart, guides, and error help, not only a reference.
- Make the contract the single source of truth and put the explanations in it.
- Document behavior at the edges: empty results, nulls, retries, limits, and failures.
- Execute examples and validate responses so that documentation cannot silently drift.
- AI drafts descriptions from code and plays the first-time integrator; tests and people decide what is true.
What’s Next?
API documentation serves people outside the codebase. Next, we turn to the people inside it: how to document code so that it explains intent and survives change.