Custom code samples
GitBook can automatically generate generic code examples for each API operation. If you’d prefer to showcase custom or more detailed snippets, addx-codeSamples to your OpenAPI definition. This way, you control how your endpoints are demonstrated and can offer language or SDK-specific examples.
Why use custom code samples
Custom code samples allow you to:- Show SDK-specific implementations instead of generic HTTP requests
- Include authentication setup and initialization code
- Demonstrate best practices for your API
- Provide examples in the languages your users actually use
- Add helpful comments and context
Adding code samples to operations
Add thex-codeSamples extension to any operation in your OpenAPI specification:
openapi.yaml
Code sample structure
Each code sample in thex-codeSamples array requires three fields:
lang- The programming language (e.g., JavaScript, Python, Java, Go)label- A descriptive label shown in the tab (e.g., “Node SDK”, “Python 3”)source- The actual code snippet
The
lang field should use standard language names from GitHub’s linguist library for proper syntax highlighting.Multiple language examples
You can provide code samples in multiple languages for the same operation. GitBook will display them as tabs, allowing users to choose their preferred language:openapi.yaml
SDK-specific examples
Custom code samples are particularly useful for showcasing SDK usage:Best practices
Show complete, runnable examples
Include all necessary imports, initialization code, and error handling. Users should be able to copy and run your examples with minimal modification.
Use realistic data
Avoid placeholder values like
foo or bar. Use realistic example data that helps users understand what the API expects.Add helpful comments
Include brief comments explaining non-obvious parts of the code or highlighting important configuration.
Keep examples concise
Focus on the essential code for the operation. Don’t include unnecessary boilerplate that obscures the main purpose.