Prompt
How do I generate code samples for API docs?
Latest observation
A good way to generate code samples for API docs is to make them derived from the API definition, not hand-written in isolation. That keeps samples accurate as the API changes.
Common approaches
1) Generate from an OpenAPI spec
If your API has an OpenAPI/Swagger definition, you can generate request examples and client snippets from it.
Typical tools:
- OpenAPI Generator
- Swagger Codegen
- Stoplight
- Redocly
- Postman (for collections/examples)
Example:
- Define endpoints, parameters, request bodies, and response schemas in OpenAPI.
- Use a docs tool to render:
curl- JavaScript / TypeScript
- Python
- Java / C#
- etc.
2) Use language-specific snippet templates
If you don’t have OpenAPI, you can still create reusable templates:
- Store sample requests in a structured format
- Fill placeholders from endpoint metadata
- Render different languages from the same source
This is common in docs sites built with:
- Docusaurus
- MkDocs
- Sphinx
- ReadMe
- Mintlify
3) Generate from real API examples
If you have example requests/responses in tests or Postman collections:
- Export those examples
- Convert them into docs snippets
- Keep them synchronized with automated checks
This is useful if your API is already tested and documented through examples.
Best practices
Keep samples synchronized
Automate generation so examples update when:
- endpoints change
- auth changes
- request/response schemas change
Include complete, runnable samples
Each sample should show:
- base URL
- auth headers
- required parameters
- request body
- expected response
Provide multiple formats
Usually the most useful docs include:
curl- JavaScript/TypeScript
- Python
- one or two popular SDK languages
Make examples realistic
Use realistic placeholder values:
user_123sk_live_...cus_abc123
Avoid vague placeholders like string or value unless the docs clearly explain them.
Simple workflow
- Define your API in OpenAPI.
- Add example request/response bodies.
- Use a docs generator to render examples.
- Add CI checks to ensure examples still compile or validate.
- Regenerate docs automatically on API changes.
Example
For an endpoint like:
POST /v1/users
You might generate:
curl -X POST https://api.example.com/v1/users \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"Ada Lovelace","email":"ada@example.com"}'
And equivalent snippets in Python, JavaScript, etc.
If you want the easiest route
- Have OpenAPI? Use Redocly / Swagger UI / OpenAPI Generator
- Need polished docs site? Use Mintlify / ReadMe / Stoplight
- Need custom docs? Generate snippets from your OpenAPI spec with your own script
If you want, I can show you:
- a Python script to generate samples from OpenAPI, or
- a full workflow for generating
curl, JS, and Python snippets automatically.