Prompt
How do I generate code samples in API docs automatically?
Latest observation
To generate code samples in API docs automatically, the usual approach is to derive them from your API definition and/or record real client examples, then plug that into your documentation pipeline.
Common approaches
1) OpenAPI-driven generation
If you already have an OpenAPI/Swagger spec, you can generate request/response examples and code snippets from it.
- Pros: consistent, automated, keeps docs in sync
- Cons: examples can be generic unless you enrich the spec
Tools:
- Swagger UI / Redoc / ReDocly for displaying examples
- OpenAPI generators to create client snippets in multiple languages
- Docs platforms like:
- ReadMe
- Stoplight
- Redocly
- Apiary
- Postman
Best practice: add example / examples fields to your OpenAPI schemas so generated snippets are realistic.
2) Record and publish live examples from SDKs/tests
Generate snippets from:
- integration tests
- SDK usage examples
- cURL scripts
- Postman collections
This keeps samples aligned with what actually works.
Good pattern:
- Write example calls in your language SDK or test suite
- Use a doc build step to extract those snippets into the docs
- Fail CI if examples stop matching the API
Tools that help:
- doctest-style extraction
- literate programming tools
- custom scripts to pull code blocks from sample files
3) Use doc generation tools that support snippets natively
Some docs systems can generate or embed language-specific snippets automatically from endpoint definitions.
Examples:
- Postman documentation
- ReadMe API Explorer
- Redocly snippets
- OpenAPI Generator for client examples
- Fern, Speakeasy, Bump.sh for doc + SDK workflows
A practical setup
Option A: OpenAPI + snippet generator
- Maintain an accurate OpenAPI spec
- Add request/response examples
- Use a snippet generator to render:
- cURL
- JavaScript
- Python
- Go
- Java
- Inject generated snippets into docs during build
Option B: SDK examples as source of truth
- Put examples in
/examples - Use them in tests
- Extract them into docs
- Verify in CI
Example workflow
If you have an OpenAPI spec, your pipeline might look like:
- Developer updates endpoint/spec
- CI validates OpenAPI
- A script generates code samples for each endpoint/language
- Docs site rebuilds with updated samples
- Published docs always show current examples
Key recommendation
If you want the least manual maintenance, use OpenAPI as the source of truth and generate code samples from it, while adding real example payloads to the spec.
If you want, I can also show:
- a sample OpenAPI file with generated snippets
- a CI pipeline example
- or recommended tools based on your stack (e.g. React, Docusaurus, MkDocs, Swagger UI, etc.).