API Documentation Best Practices
What is API Documentation
Introduction
• High-Level Definition
A human-readable guide explaining how developers enable machines to communicate.
It helps humans (especially developers) understand how to use APIs to build system integrations.
• Purpose
o Supports inter-machine communication.
o Helps developers create, consume, and integrate APIs.
o Acts as a bridge between technical implementation and external usage.
Types of Documentation
1. Product Documentation
o Guides users through a UI or workflow.
o Focused on point-and-click use.
o Not always API-related.
2. API Documentation
o Developer-centric, but also consumed by non-developer roles.
o Helps people write code that uses APIs.
o Includes endpoint descriptions, parameters, examples, auth mechanisms, etc.
Who is it for?
• Primary: Developers (the implementers).
• Secondary: Business stakeholders, product managers, security teams, IT leadership.
“Developers try, business buys.”
Devs evaluate APIs for usability and integration potential.
Business teams often make the final purchasing or partnership decisions.
• Dual Audience Strategy
Docs must speak to:
o Technical clarity for developers.
o Business value and reliability for decision-makers.
Internal vs External Documentation
• Internal API Docs
o Used by internal teams.
o Often includes proprietary details (e.g., team contacts, infrastructure links, metrics).
o Auth and access patterns are typically simpler and looser.
• External API Docs
o Shared with partners, clients, or public users.
o Treated as a product: polished, branded, clear, and secure.
o May be monetized or require signup/invitation to access.
o Requires strong developer experience and trust-building.
• Blurring Lines
o Internal docs are increasingly adopting external-facing practices (branding, dev experience).
o Both need to support the complete developer journey: understanding, building, and
maintaining.
Key Considerations for API Docs
• Know your audience (technical vs business).
• Define if it's for internal or external use.
• Align docs with the broader developer experience.
• Adapt your voice and depth based on context.
Types of API Documentation
What is API Documentation?
API documentation is a structured explanation of how to effectively interact with an API. It guides developers
through using API endpoints, understanding their capabilities, parameters, responses, authentication methods,
error handling, and more. While “documentation” is a broad term, API documentation typically breaks down
into a few core types, each with distinct goals and audiences.
Three Main Types of API Documentation
1. Reference Documentation
This is the technical core of API documentation. It’s intended for developers who already understand the API’s
purpose and are ready to write code. It acts as an encyclopedia with precise details for how to make calls.
o Lists endpoints, request types (GET, POST, etc.), URLs, query and path parameters.
o Includes required headers, authentication details, and content types.
o Provides sample requests and responses.
o Often includes data type definitions and schema for response objects.
o Explains HTTP status codes and associated error formats.
Example: PagerDuty API
o GET /escalation_policies lists existing policies.
o Shows parameters like offset, limit, and required headers.
o Error handling details include response structure and potential status codes like 400 (client
error) or 500 (server error).
o Response field descriptions are critical—ambiguous terms like summary must be clearly
explained.
2. Conceptual Documentation
This focuses on the why and what rather than the how. It’s ideal for non-developers, new developers, or
decision-makers evaluating the API.
o Explains business logic and key ideas behind the API.
o Defines entities and relationships (e.g., what is an “escalation policy”?).
o May include system overviews, use cases, and related concept links.
o Offers a more narrative and explanatory tone to help users understand the bigger picture.
Example: PagerDuty Concepts Page
o Goes deeper into what escalation policies do, how they relate to users, incidents, and
schedules.
o Serves as a bridge between functional descriptions and reference details.
3. Task-Based Documentation (Workflows or Guides)
These are step-by-step guides that walk users through completing specific tasks with the API. They may include
code samples, sequences of API calls, and practical scenarios.
o Focuses on workflows like "Create a Payment" or "Send a Notification."
o Often includes interactive “Try it” sections or API explorers.
o Shows how multiple endpoints and concepts come together in a real-world task.
o Connects conceptual knowledge and reference details in a tangible use case.
Example: Stripe Task Guide
o “Start an Integration” outlines concrete steps.
o Covers everything from API key setup to making the first call.
o Code samples and sandbox/test environments help users experiment safely.
Key Features and Considerations in API Documentation
• Errors and Status Codes
o Documentation must define what users can expect when requests go wrong.
o HTTP codes (200, 400, 500) should be explained alongside custom application-level error codes.
o Error shapes should be consistent across endpoints to reduce complexity in client error
handling.
o Good docs often include human-readable messages and reference links to explain error codes
further.
• Authentication and Getting Started
o The most important first step for new users. Should be crystal clear.
o Should walk users through how to obtain and use credentials (e.g., API keys, OAuth tokens).
o Ideally, there's a single, unified auth mechanism for all APIs in a platform.
o Auth issues often block progress, so this is a critical area to invest in clarity.
• Interactive Features
o Tools like “Try It” buttons allow users to test endpoints with real or mock data.
o Helps users see real responses and experiment without writing code immediately.
o Copy-pasteable examples in languages like cURL, Python, or JavaScript are valuable for fast
onboarding.
• Content Negotiation and Versioning
o APIs often support multiple response formats; documentation should clarify how to request
them.
o Custom media types and versioning schemes (e.g., via headers or URL paths) must be clearly
explained.
o Consistency in versioning is key to long-term maintainability.
• Consistency and Reuse
o Parameters like paging (offset, limit) and error formats should be uniform across endpoints.
o Reduces the learning curve and implementation time for clients.
o Documentation should help developers recognize these reusable patterns.
Final Thoughts
• Clear, consistent, and comprehensive documentation is both a usability and a security win.
• Reference docs help developers write code; conceptual docs explain meaning; task docs demonstrate
workflows.
• Great API documentation supports fast onboarding, fewer errors, and deeper understanding.
• Error documentation not only supports users but also surfaces quality and security flaws.
• The first-time user experience should be polished—aim to get users from zero to a working API call in
under 5 minutes.
Value of Good Documentation
Good documentation is a powerful enabler in both internal and external contexts. When executed well, it
serves as an educational tool, organizational framework, support system, marketing asset, and innovation
catalyst.
What is API Documentation
API documentation is a structured and comprehensive resource that explains how to effectively use and
integrate with an API. It serves as a reference guide for developers, outlining available endpoints, data formats,
request/response structures, authentication mechanisms, and other necessary technical details.
Why Documentation Matters
1. Education and Enablement
• Documentation educates various audiences: customers, prospects, partners, and internal teams.
• Serves as the single source of truth about what the company does and how its APIs can be used.
• Helps non-technical stakeholders, like business leaders, understand technical capabilities.
• Empowers internal teams with shared knowledge of platform-wide API capabilities.
2. Defines Product Boundaries
• API documentation helps define logical product and service boundaries.
• Encourages intentional platform design (inverse Conway maneuver), where APIs reflect the desired
architecture rather than current organizational structure.
• Clear boundaries assist in understanding, securing, and testing services.
3. Supports Comprehension and Discover ability
• Well-documented APIs make it easy for consumers to:
o Understand the overall architecture.
o Drill down into specific technical details.
o Find related functionality quickly.
• Enhances on boarding for new users and developers, leading to faster adoption.
4. Improves Support Experiences
• Reduces reliance on ad-hoc support such as emails, meetings, or hallway conversations.
• Directs users toward appropriate support channels:
o Self-service solutions
o Community forums
o Ticketing systems
• Minimizes friction and confusion by embedding support guidance within documentation.
5. Enables Developer Marketing
• Developers are a skeptical audience with a low tolerance for sales fluff.
• Documentation plays a key role in teaching over selling.
• Linking new features and updates to documentation (e.g., changelogs) boosts credibility and adoption.
• First impressions matter—excellent documentation leads to positive developer experiences and
community growth.
Who Benefits from Good Documentation
Internal Benefits
a. Avoids Duplicated Efforts
• Lack of documentation leads to repeated solutions for the same problems.
• Developers unaware of existing APIs may build redundant or bespoke systems.
b. Encourages Shared Leverage
• Promotes building reusable, scalable components rather than narrow, one-off integrations.
• Aligns teams towards common capabilities and goals.
c. Builds Organizational Understanding
• Without documentation, knowledge becomes tribal and informal.
• Encourages dependency on specific individuals or informal communication.
• Formal documentation creates clarity, transparency, and consistent knowledge sharing.
External Benefits
a. Boosts Adoption
• Comprehensive, accessible, and well-organized documentation helps potential users quickly
understand and begin using the API.
• The quality of documentation often influences whether a developer will adopt the API at all.
b. Improves Relationship with Users
• Well-maintained documentation shows professionalism and respect for the consumer's time.
• Sets a positive tone for partnerships and third-party developer engagement.
c. Enhances Developer Experience
• Great documentation makes it easy to:
o Learn the API
o Test features
o Troubleshoot issues
• Developers are likely to recommend APIs they enjoy using, contributing to organic growth through
word of mouth.
Summary
Investing in API documentation is not just a technical necessity—it's a strategic move. It:
• Facilitates education and onboarding
• Defines and secures system architecture
• Streamlines support
• Fuels developer marketing
• Strengthens internal collaboration
• Enhances external adoption and reputation
Top 3 Reasons Documentation is a Must-Have
API documentation is a structured, comprehensive resource that explains how to interact with an API. It
typically includes:
• Available endpoints and methods
• Authentication and authorization processes
• Request and response formats
• Status codes and error handling
• Usage examples and workflows
It serves as both a reference and a guide for developers, internal teams, and external partners—supporting
understanding, integration, and safe usage of the API.
Top 3 Reasons Documentation is a Must-Have
1. Reduces Security Risks
Documentation plays a critical role in identifying and preventing security flaws before APIs reach production.
a. Catches Missing or Inconsistent Auth Mechanisms
• Lack of clear authentication and authorization details is a top cause of API exploits.
• OWASP API Top 10 (2023) lists Broken Object Level Authorization (BOLA) and Broken Authentication
as the top two risks.
• When documenting, the absence of details like how to obtain and attach a token becomes immediately
visible, acting as a preemptive red flag.
b. Establishes Consistent Auth Patterns
• Inconsistent authentication patterns across different APIs often signal poor design decisions.
• Documentation forces teams to align and standardize these critical components.
c. Integrates Audit and Review by Default
• When documentation is updated iteratively alongside API changes, it provides a natural review process.
• Even if the documentation writer is not a security expert, clear gaps or deviations can be flagged and
escalated.
• Encourages integration with broader API review processes (e.g., style guides, design audits).
2. Prevents Zombie and Shadow APIs
Zombie or shadow APIs are undocumented, forgotten, or rogue APIs that exist in production without oversight.
a. Major Security and Operational Risk
• These APIs may still be accessible, but no one knows what they do, how they authenticate, or whether
they’re secure.
• They often become blind spots in risk assessments, monitoring, and incident response.
b. Widespread Impact
• A Nordic APIs survey showed 94% of organizations experienced incidents involving undocumented
APIs.
• These APIs tend to go unmonitored and can produce performance issues or serious vulnerabilities.
c. Maintains an Accurate, Living API Catalog
• Comprehensive documentation creates visibility into what APIs exist.
• Maintained portals or repositories of documented APIs help teams understand, manage, and secure
the full inventory.
• If you don’t know it exists, you can’t protect it.
3. Prevents API Sprawl and Duplicated Effort
APIs built without documentation often contribute to platform fragmentation and inefficiency.
a. API Sprawl
• Refers to a situation where too many similar APIs are created without clear coordination or reuse.
• Can happen even when there's some vague awareness of existing APIs, but no shared documentation
or agreed platform understanding.
b. Cognitive Misalignment
• Without documentation, teams lack a shared mental model of:
o What APIs exist
o What functions they perform
o How they interrelate
• Results in fragmented solutions and limited reusability.
c. Promotes Alignment and Reuse
• Centralized, well-structured documentation fosters cognitive alignment across teams.
• Enables shared leverage, reduces redundancy, and increases platform cohesiveness.
• Allows developers to recognize where existing APIs can be reused or extended instead of reinvented.
Summary
Top 2 Reasons Documentation is Nice-to-Have
API documentation is a structured and user-focused guide that explains how to effectively use and interact
with an API. It typically includes:
• Endpoint descriptions and parameters
• Authentication and authorization methods
• Request/response formats and examples
• Error handling and status codes
• Usage patterns and workflows
Its purpose is to provide clear, consistent instructions and references that help developers integrate,
troubleshoot, and build with an API confidently.
Top 2 Reasons Documentation is Nice-to-Have
While some documentation justifications are rooted in risk and security (must-haves), others focus on positive
outcomes and improvements to developer experience, collaboration, and platform growth. These “nice-to-
haves” are still highly impactful and motivating.
1. Observability
Documentation promotes system-wide visibility and understanding of your API landscape.
a. Clarity Over Chaos
• Acts as the opposite of API sprawl and shadow APIs.
• With proper documentation, teams gain a clear, centralized view of all available APIs, what they do,
and how they connect.
b. Improves Navigation and Decision-Making
• Allows stakeholders to understand:
o Which APIs exist
o Their purposes and dependencies
o How they fit into the broader platform
• This informed visibility reduces confusion and improves architectural and product decisions.
c. Facilitates Governance and Maintenance
• Teams can more easily monitor:
o API ownership
o Lifecycle status (e.g., deprecated vs. active)
o Usage metrics and versioning
• Creates a foundation for better long-term API lifecycle management and governance.
2. Shared Leverage and Collaboration
Documentation builds a foundation for cross-team alignment and shared value creation.
a. Encourages Reusability
• When APIs are clearly documented and discoverable, developers are more likely to:
o Reuse existing APIs
o Avoid writing one-off, redundant code
• This helps create a more modular, efficient system.
b. Strengthens Team Collaboration
• Promotes a collaborative culture where teams share, extend, and contribute to common services
rather than building in silos.
• Documentation becomes a communication layer between developers, teams, and stakeholders.
c. Accelerates Innovation
• Frees teams from solving the same problems repeatedly.
• Encourages experimentation and faster integration of new ideas using existing, well-understood
capabilities.
Summary
Who Writes the Docs Anyway?
What is API Documentation
API documentation is a structured, user-oriented reference that explains how to interact with an API. It
typically includes:
• Endpoint references
• Input/output schemas
• Authentication methods
• Request/response examples
• Error handling guides
• Integration patterns and workflows
It is intended to guide and support developers and consumers in understanding, using, and troubleshooting
the API effectively.
Who Writes the Docs Anyway?
Creating effective API documentation requires contributions from multiple roles—each with unique strengths
and limitations. The best results often come from collaboration, not isolation.
1. Developers
Developers are usually the first people thought of when API documentation is discussed.
Pros:
• Deep understanding of implementation details.
• Can provide accurate technical information about how the API works.
• Peer developer reviews help ensure developer-centric clarity.
Cons:
• Tend to write from a system-centric perspective, focused on how it was built rather than how it is used.
• May overlook beginner-friendly or customer-focused explanations.
• Writing documentation is often a lower priority for devs, especially under tight delivery timelines.
Recommendation:
• Developers must be involved, but ideally through collaborative peer reviews, especially during
development.
• Their input is essential for technical accuracy and completeness.
2. Product Managers (PMs)
Product managers—especially API product managers—often contribute to or review documentation.
Pros:
• Bring a customer-centric perspective focused on usability and clarity.
• Emphasize the “why” and “what” of the API rather than just the “how.”
• Help bridge technical functionality with business value.
Cons:
• May lack deep technical understanding, leading to misrepresentation or oversimplification of technical
concepts.
• Risk of producing documentation that is readable but technically vague or inaccurate.
Recommendation:
• Involve PMs in partnership with developers to co-define functional behavior and user expectations.
• Let them shape the user journey and use case context, while devs ensure accuracy.
3. Technical Writers
Technical writers are communication professionals specialized in writing clear, precise, and structured technical
content.
Pros:
• Experts in simplifying complex topics for various audiences.
• Ensure consistent structure, voice, and tone across documentation.
• Can act as implicit quality assurance (QA)—flagging unclear logic, inconsistencies, or gaps.
Cons:
• Cannot operate in isolation—need context, technical walkthroughs, and early involvement.
• If involved too late, may struggle to reconstruct the product's intent from incomplete inputs.
Recommendation:
• Ideal contributors when available, especially in API-first organizations.
• Involve technical writers early, even at the abstract/planning stage.
• Support them with a clear style guide, internal standards, and ongoing access to developers and PMs.
Best Practices for Documentation Workflow
1. Start Early, Iterate Often
o Begin documenting high-level API behavior even before implementation.
o Continuously update as features evolve.
2. Collaborate Across Roles
o Blend technical depth (devs), customer empathy (PMs), and communication skill (tech writers).
o Use documentation as a feedback and validation tool throughout the development cycle.
3. Embed Documentation in the Development Process
o Make documentation a first-class citizen, not an afterthought.
o Treat it as part of the delivery scope—not a post-release task.
4. Use Style Guides and Standards
o Standardize formatting, terminology, and tone.
o Reduce cognitive friction for readers and ensure consistency across APIs.
5. Enable Peer Review
o Encourage team members, especially other developers, to review docs regularly.
o Use this to catch errors and improve clarity before external release.
The Business Impact of API Documentation
Good docs matter to security
Why API Documentation Matters for Security
API documentation plays a critical role in the security posture of a platform. While many organizations treat
documentation as an afterthought, its influence on security, consistency, quality, and maintainability is
substantial.
Detecting Security Issues Through Documentation
Good documentation enables security teams to:
• Review authentication and authorization patterns before code is written.
• Identify inconsistencies across services or endpoints that may lead to vulnerabilities.
• Perform security reviews early in the development life cycle, reducing the chances of rushed, post-
development fixes.
Consistency Through Standardization
• Consistency is a byproduct of standardization.
• Documentation reveals areas where systems behave inconsistently—such as mismatched error
responses or different authentication mechanisms.
• A consistent API helps in building a platform mindset, not just a collection of services.
Documentation Reveals Quality Issues
Tech writers, especially those writing from the perspective of API consumers, can surface:
• Error-handling deficiencies
• Logical flaws in how the API operates
• Missing or conflicting functional descriptions
These insights lead to better testing coverage, as QA teams can understand intended behavior early in the
lifecycle.
Early Documentation = Early Risk Reduction
• Security and DevOps teams can't protect assets they don't know exist.
• When APIs are pushed without documentation, undocumented or "shadow" assets increase attack
surface.
• If documentation exists—even if rough—those teams can:
o Prepare mitigation strategies.
o Ask deeper, more specific questions.
o Engage in early security reviews.
Undocumented APIs = Increased Risk
• Poor, outdated, or missing documentation is a leading cause of security exposures.
• The goal isn’t perfection but reasonable quality and existence of documentation.
• Reasonable documentation mitigates risk by reducing blind spots.
Secure-by-Design Approach Using Documentation
Shift Security Left With Design-First Mindset
• Document before building to outline:
o What the API does
o What it will look like
• This avoids mid-implementation surprises or rework due to overlooked security flaws.
Pre-Implementation Security Review
• With an early description in place, you can:
o Review authorization patterns
o Identify 80% of potential API exploits before writing a single line of code
• Late-stage review after production deployment misses this window of opportunity.
API Style Guides as Security Tools
What Is an API Style Guide?
• A set of standardized design principles that guide how APIs are structured.
• Promotes:
o Consistent naming conventions
o Consistent authentication methods
o Predictable error formats
Security-Focused Style Guide
• A subset of the broader API style guide focusing specifically on:
o Auth standards
o Data handling rules
o Rate-limiting mechanisms
o Input validation practices
o Other security-critical areas (e.g., currency handling in payment APIs)
Calling it a "style guide" instead of a "standard" helps reduce resistance from developers who may view
standards as rigid or bureaucratic.
Long-Term Benefits of Early Security Documentation
• Embedding security checks into early design processes builds defensive depth over time.
• Documented and repeatable security rules enable:
o Continuous integration of best practices
o Prevention of recurring vulnerabilities
o Scalable security across growing systems
Summary
Investing in API documentation isn’t just about clarity—it’s a proactive security control. Good docs allow for:
• Early risk detection
• Better testing
• Collaboration across DevOps and Security
• Long-term standardization
Poor or missing documentation leads to unmonitored, exploitable assets. Reasonable, timely documentation
paired with design-first thinking and API style guides significantly improves a platform’s resilience to attack.
Good docs matter for improved governance
While often viewed negatively, governance in the context of API development doesn’t have to be bureaucratic
or obstructive. When implemented through automated, documentation-driven processes, governance
becomes an enabler of quality, consistency, and scale.
A healthy documentation process is the foundation of strong, modern governance.
Automating Consistency with Style Guides
Consistency is what transforms a collection of APIs into a cohesive platform. But ensuring that every API
adheres to consistent patterns—naming, authentication, formatting, and even documentation—is extremely
difficult when done manually.
Manual API reviews are:
• Time-consuming
• Prone to human error
• Not scalable
The solution is automated governance through tooling, especially Style Guides and linting.
API Style Guides + Linting
Tools like Stoplight provide rule sets to define API governance policies. These can include rules for both:
• Technical design (e.g., HTTP method use, schema formatting)
• Documentation quality (e.g., required descriptions, contact info, usage examples)
Example rule:
"info.contact": should contain a contact object
This kind of rule ensures that every documented API includes contact details, reducing confusion and ensuring
accountability. Rather than relying on humans to catch these omissions, linting tools flag them automatically.
Automating Documentation Quality
Linting tools like Stoplight Spectral or Redocly CLI allow you to set policies such as:
• All response fields must include a description.
• contact or termsOfService must be present in info object.
• Tags must have descriptions.
• Deprecated endpoints must be documented explicitly.
By automating these checks:
• Human reviewers can focus on higher-level questions like:
o Is this API necessary?
o Is the interface reusable?
o Is the design sound?
• You avoid wasting time on repetitive, low-value checks.
Enforcing Writing Style with Vale
Beyond structural rules, Vale helps enforce consistent language and tone in API documentation. It is a linter
for prose, enabling:
• Enforcement of organizational voice and tone (e.g., Microsoft Style Guide)
• Control over acronym usage
• Rejection of vague or discouraged phrases
• Standard phrasing across docs
This contributes to professional, consistent technical writing, ensuring clarity and ease of understanding
across your docs.
Benefits of Automating Governance
1. Scalability
o You can apply the same checks across hundreds of APIs, regardless of who wrote them.
2. Reusability
o Common, standardized patterns are easier to reuse across teams and projects.
3. Improved Developer Experience
o Developers appreciate clean, predictable interfaces and docs.
o Familiarity across APIs reduces learning curve and cognitive load.
o A consistent look and feel builds trust in the system.
4. Cognitive Efficiency
o Automating lint-level tasks frees engineers and reviewers to focus on meaningful design
discussions.
5. Better Governance Without Bureaucracy
o Style guides and linting replace heavy-handed processes with continuous, lightweight
enforcement.
Final Thought
Good documentation governance isn’t about slowing things down—it’s about empowering teams to produce
high-quality APIs at scale. Through automation, style enforcement, and clear documentation rules, you create
a system that supports growth, reduces risk, and delights developers.
Good docs matter for partnership
Why Documentation Is Critical for Partner Success
In partnership-driven ecosystems, API documentation becomes one of the most important assets shared
between companies—especially in early engagement phases.
If you want to onboard partners efficiently, documentation acts as the first touchpoint, setting the tone for
how collaboration will unfold.
Key Impacts of Documentation on Partnerships
1. Brand Affinity
Well-crafted documentation directly influences how partners perceive your brand.
• A polished, easy-to-navigate developer portal reflects technical maturity and professionalism.
• A seamless onboarding experience means fewer support requests, less friction, and more trust.
• If a partner repeatedly encounters missing or confusing documentation, they may form a negative
impression of your company—even before any technical integration starts.
Example:
Stripe is often cited in developer communities as having excellent API documentation. That documentation
contributes significantly to the brand loyalty and positive sentiment developers have toward the company—
even without any human interaction.
In this way, documentation becomes an unspoken form of marketing, building credibility and affinity through
clarity and usability.
2. API Adoption
After investing time and effort into building an API, adoption becomes a critical success metric.
• If the documentation is poor, difficult to follow, or incomplete, adoption will suffer—even if the API
itself is technically sound.
• High-quality documentation accelerates time-to-value for developers:
o They integrate faster
o They ask fewer questions
o They are more likely to recommend the platform to others
Documentation is one of the most effective levers you have to boost adoption.
3. Scalability
You cannot scale a partner ecosystem or developer program without consistently good documentation.
• Without centralized, automated, and standardized documentation practices:
o Each new partner relationship becomes a one-off engagement
o Support and onboarding require manual, high-touch effort
o Teams struggle to repeat success or track progress
Good documentation enables:
• Self-service onboarding
• Reduced dependency on engineering support
• Repeatable integration models
• Faster partner rollout at scale
In short, scaling partnerships is impossible without scalable documentation.
Summary
API documentation is not just a developer tool—it’s a strategic business asset. In partnership contexts, it
directly impacts:
• Brand perception
• Adoption rates
• Scalability of integrations and relationships
When treated seriously, documentation builds trust, drives usage, and supports growth. When ignored, it
becomes a bottleneck to everything from business development to engineering productivity.
How to Write Good Documentation
How to Write Good Documentation
Start With the Audience
Before writing a single line of documentation, you must define who you're writing for:
• Internal developers: Typically more familiar with system internals; concise, technical tone preferred.
• External partners or customers: May need more detailed context, examples, and simplified
explanations.
• Security or compliance teams: Might need visibility into auth flows, data handling, and risk-sensitive
areas.
Tailor voice, structure, and depth based on the audience's background and needs.
Key Elements of Good API Documentation
A complete API document should clearly explain the who, what, where, and how of each endpoint. The
following elements must be included:
1. Request Structure
• Required vs Optional Fields
Clearly state which fields (including versioning, headers, query parameters, etc.) are mandatory.
Example:
o v1 in /api/v1/resource might be required
o If omitted, does the API default to the latest version?
• Authentication Requirements
Document expected headers (e.g., Authorization: Bearer <token>) and any preconditions for access.
• Endpoint Path
Specify the full URL structure:
o Example: POST /api/v1/users/{id}/reset-password
• HTTP Methods
Include the verb for each operation (e.g., GET, POST, PATCH, DELETE, etc.).
• Request Data
o Body schema (for POST, PUT, PATCH)
o Query string parameters
o Header values
Include field names, types, descriptions, required/optional flags, and example values.
2. Response Structure
• Response Format
Show example JSON (or XML) responses for:
o Success (2xx) responses
o Client error (4xx) responses
o Server error (5xx) responses
• Status Codes
Document every potential HTTP status code and its meaning in the context of the specific API.
Example:
o 200 OK – Request successful
o 400 Bad Request – Missing required fields
o 401 Unauthorized – Invalid or missing auth token
o 500 Internal Server Error – Unexpected failure
• Response Field Descriptions
Include what each field in the response means, especially for complex objects or nested data.
3. Versioning Behavior
If the API supports versioning:
• Clarify how versions are specified (e.g., path, query param, or header).
• Explain what happens if version is not supplied.
• Define the default behavior (e.g., does it upgrade silently or return an error?).
4. Discoverability & Navigation
• Centralized Access
Documentation should be published and accessible via a developer portal or public docs site, not sent by email
or stored in private files.
• Navigation Structure
o Include indexes or tables of contents.
o Link related endpoints together.
o Enable search and filtering (if hosted in a portal).
• Cross-referencing
Use links for:
o Related terms or definitions
o Shared schemas
o Global headers or auth mechanisms
Testing the Documentation
Internal Validation
• Peer Review
Have internal developers who did not build the API review the docs. They bring fresh eyes to edge cases and
usability issues.
• Simulated Use
Ask team members to:
o Try to follow the documentation to call the API
o Note confusing parts or missing explanations
o Report unclear terminology
• Observe Friction Points
Watch where readers get stuck:
o Ambiguous error codes
o Confusing authentication flows
o Inconsistent naming or field behavior
Developer Advocacy Feedback Loop
If you have developer relations or advocacy teams, use them to:
• Run real-world testing of docs
• Gather feedback from community and partners
• Suggest improvements in clarity, completeness, or consistency
Even without a formal DevRel team, create a feedback process that includes non-developers or client-facing
teams.
Special Focus: Authentication
• Most users will fail at authentication on their first attempt if not documented clearly.
• Ensure:
o Auth methods are explained step-by-step
o Token generation, expiration, and renewal processes are documented
o Example headers and curl/Postman commands are provided
Authentication is often the first integration step—if it fails, the entire API is unusable.
Summary Checklist for Writing Good API Documentation
Documenting a Fake API – Best Practices & Full Walkthrough
Overview
This exercise walks through the process of documenting a fake API — a "Widget API" — using modern practices
and OpenAPI 3.1, with Stoplight as the platform. It demonstrates how to craft useful API documentation that’s
both clear and developer-friendly.
1. API Overview
Key Elements to Include:
• API Version
Indicates the current version, e.g. v1.
• Base URL and Mock Server
o Base: https://api.widgets.com/v1
o Mock: Simulated URL for development/testing purposes.
• Security Information
Describe how to authenticate (API Key, OAuth, etc.)
• Contact, License, Terms
Optional but important for production APIs.
• API Description
A short summary explaining what the API does. For example:
"The Widget API allows consumers to manage and retrieve widget data."
2. Getting Started Section
Must-Haves:
• Authentication Requirements
Explain what users must do to access the API (e.g. obtain an API key).
• Quickstart Instructions
List steps to make the first successful API call.
• Concepts
Define key repeated concepts like pagination (page, pageSize), authentication flows, and error structures.
3. Documenting Endpoints
Example: GET /widgets
Summary:
Retrieve a list of widgets.
Security:
Document security requirements again at the operation level.
Query Parameters:
• page (integer): Page number, default = 1.
• pageSize (integer): Number of results per page, default = 10.
Response (200 OK):
{
"page": 1,
"total_pages": 10,
"items": [
{
"id": "abc123",
"name": "SuperWidget",
"sku": "SW12345"
}
]
}
• Fields Description:
o id: Unique identifier (string).
o name: Required. Length 1–50 characters.
o sku: Required. Matches regex pattern like [A-Z]{2}\\d{4,}.
Example Constraints:
• name: minLength = 1, maxLength = 50
• sku: pattern = "^[A-Z]{2}[0-9]{4,}$"
Example: POST /widgets
Summary:
Create a new widget.
Request Body (application/json):
{
"name": "WidgetName",
"sku": "WDGT0012"
}
• id is autogenerated.
• name and sku are required.
Response (200 OK):
Returns the created widget object including auto-generated id.
Errors:
• 400 Bad Request: Invalid input data.
• 401 Unauthorized: No or invalid API token.
• 403 Forbidden: Valid token but no access.
• 500 Internal Server Error: Unexpected error; user should contact support.
4. API Error Documentation
Use a consistent error model across the API:
{
"error": {
"code": "INVALID_REQUEST",
"message": "The provided 'sku' does not match required format.",
"details": []
}
}
Explain error codes and meanings clearly in the "Getting Started" or a separate Errors section.
5. OpenAPI Specification Structure (YAML/JSON)
• Uses OpenAPI 3.1
• Info Section:
Includes title, version, description.
• Servers:
Lists live and mock base URLs.
• Paths:
Every endpoint under /widgets includes both GET and POST operations.
• Components/Schemas:
Shared definitions like:
components:
schemas:
Widget:
type: object
required: [name, sku]
properties:
id:
type: string
name:
type: string
minLength: 1
maxLength: 50
sku:
type: string
pattern: '^[A-Z]{2}[0-9]{4,}$'
WidgetListPaged:
type: object
properties:
page:
type: integer
default: 1
total_pages:
type: integer
items:
type: array
items:
$ref: '#/components/schemas/Widget'
• Security Schemes:
Defined globally with optional operation-level overrides.
6. Tools and Features to Enhance Developer Experience
• Example Requests/Responses:
Always include request/response samples to aid understanding.
• Try-It Interface / Mock Server:
Allow users to test endpoints directly.
• Code Samples:
Provide curl/HTTP examples and optional SDK snippets.
7. Using Markdown for Documentation
Documentation bodies use markdown syntax:
• # for top-level headers
• ## for subheaders
• Inline code: like_this
• Code blocks:
•
• { "example": "yes" }
•
Markdown is converted into styled, readable HTML in the developer portal.
8. General Best Practices
• Always include:
o Purpose
o Required fields
o Data types
o Field constraints (length, pattern)
o Examples (positive + negative)
o Authentication instructions
o Error responses
• Use shared schemas for reusability.
• Keep things DRY (Don’t Repeat Yourself).
• Use consistent terminology.
• Define common concepts like pagination, filtering, errors.
• Render and preview your docs continuously to verify clarity and completeness.
9. Final Tips
• Favor clarity over brevity.
• Don't skip explaining constraints or return values.
• Think like a developer: what would confuse you?
• Good documentation is more than specs — it's guidance.
Deeper Dive into Writing Good API Documentation
Context: After creating and documenting a simple fake API, it’s important to understand how to scale and
maintain good documentation effectively, especially for REST APIs.
1. Avoid Writing Docs from Scratch Manually
• Writing API documentation manually using generic tools (like Google Docs or plain HTML files) is
inefficient.
• Hand-curated docs are hard to maintain, scale, and keep consistent across teams or organizations.
• Manual approaches often lead to outdated or inconsistent documentation, which can cause confusion
and errors.
2. Use Tools that Generate Documentation
• Modern API documentation is often generated from a structured description of the API, such as an
OpenAPI (formerly Swagger) specification.
• Tools allow you to fill in the blanks: you describe your API in a structured format, and the tool
generates consistent, readable docs.
• This enables easy sharing of documentation links and faster updates as APIs evolve.
• Generated docs ensure alignment between the API’s functionality and the documentation, reducing
the risk of discrepancies.
3. Keep Documentation Up-to-Date with Functionality
• One of the most common pitfalls is that API documentation gets out of sync with the actual API
implementation.
• Especially for complex areas like authentication, if documentation is inaccurate, developers may be
blocked or misled.
• An automated approach, tied into the code base or build pipeline, helps keep documentation current
with the API.
4. OpenAPI as a Standard
• OpenAPI is a structured format for describing REST APIs without building them first.
• It supports:
o Clear definitions of endpoints, parameters, request and response schemas.
o Tools integration for documentation generation, testing, and validation.
• Many tools abstract away the raw OpenAPI syntax so you don’t have to write it manually but can still
leverage its power.
5. Examples of Great API Documentation
• Stripe is widely recognized for excellent API docs:
o Clear human-friendly descriptions for each operation.
o Easy-to-understand explanations of what each endpoint does.
o Copy-paste examples for common use cases.
• Twilio is another leader in API developer experience:
o Provides multiple language-specific code samples.
o Ensures code samples are tested with every deployment, guaranteeing they work.
o Offers “try it” features that allow developers to experiment directly within the documentation.
6. Best Practices to Adopt
• Keep example requests and responses visible and accessible.
• Provide language-specific samples if possible.
• Include interactive elements like “try it” buttons for real-time testing.
• Ensure the documentation is easy to browse and quickly searchable.
Summary
To write good API documentation, you should use tools like OpenAPI to automate creation, maintain alignment
with the API’s actual behavior, and prioritize developer usability by including practical examples and interactive
features. Studying companies like Stripe and Twilio offers valuable insights into building exceptional API
documentation experiences.
Documentation Techniques and Tools
When documenting APIs, different techniques and tools are available depending on your stage of
development, resources, and goals. Let’s explore the main approaches, their advantages, disadvantages, and
some popular tools.
1. Spec-Based Approach (Middle Ground)
• Concept:
Designing and documenting an API before it is fully built using an API specification format, such as OpenAPI
(formerly Swagger).
• Advantages:
o Centralized documentation minimizes duplicated efforts.
o Teams can collaborate effectively by sharing a common spec.
o Early feedback from potential consumers can be gathered before implementation, improving
design quality and adoption.
• Disadvantages:
o Risk of the implementation diverging from the spec, leading to outdated or inaccurate
documentation.
o Requires discipline and tooling integration to keep spec and implementation aligned.
2. Code Annotations (Left Approach)
• Concept:
Writing documentation directly inside the source code as annotations or comments that describe each
operation. Documentation is generated automatically from these annotations.
• Advantages:
o Documentation is closely tied to code, so it tends to stay in sync with implementation.
o Requires minimal additional tooling since many frameworks support generating docs from code
comments.
• Disadvantages:
o Less accessible to non-engineering roles like technical writers or product managers who might
find codebases intimidating.
o Requires engineers to have at least a stubbed implementation before documentation can begin.
o May be harder to design comprehensive documentation for consumers, as annotations focus on
code-level detail.
3. Hand-Curated / Bespoke Documentation (Right Approach)
• Concept:
Writing documentation manually using generic content management systems (CMS) or web platforms without
relying on specifications or code annotations.
• Advantages:
o No need for specialized tooling or learning specification languages.
o Simple to start and flexible in format and style.
• Disadvantages:
o Very difficult to keep documentation up-to-date and in sync with the API implementation.
o No automated tooling to generate docs or validate content, increasing manual work and errors.
o Lacks contract-based integration with other tools such as testing or SDK generation.
o Adding features like code samples, interactive “try it” buttons, or versioning requires significant
custom development.
o Not a recommended approach for modern APIs (especially in 2023 and beyond).
4. Popular Documentation Tools and Platforms
• Stoplight Platform:
o Offers open-source and free options for API design, documentation, and testing.
o Supports spec-based approaches with visual editing and collaboration features.
• Redocly:
o Focused heavily on API documentation with strong support for OpenAPI specs and
customization.
• ReadMe:
o Provides documentation hosting, API explorer features, and developer portal capabilities.
• SwaggerHub:
o Combines API design and documentation with additional features for governance and
collaboration.
• Notion:
o A more general-purpose CMS used for documentation but lacks native API spec integration and
automation. Better for hand-curated docs but limited for API-specific workflows.
• Open Source Generators:
o Numerous open-source tools exist that take API specs like OpenAPI files and generate
documentation portals, saving development time.
5. General Recommendation
• Avoid writing API documentation from scratch or building your own portal unless absolutely necessary.
• Leveraging existing tools and spec-based approaches will save time, reduce errors, and enable better
collaboration.
• Use a centralized spec that can be shared, validated, and integrated into your development lifecycle.
• Ensure your chosen platform supports automation features like validation, mock servers, and “try it”
functionality to enhance developer experien
Documentation Best Practices
1. Consider a Broad Audience
Avoid internal jargon and acronyms that could confuse readers outside your immediate team. While some
internal documents may tolerate jargon, clear language ensures accessibility and reduces friction for all users.
2. Use an Approachable Tone and Plain Language
Steer clear of buzzwords and overly formal business language. A straightforward, friendly tone helps build
rapport with developers and users, making the documentation feel welcoming and easy to follow.
3. Provide Clear and Meaningful Code Samples
Use well-named variables and functions in examples. Avoid generic or autogenerated samples that users may
find confusing. Thoughtful samples improve understanding and facilitate copy-pasting without guesswork.
4. Avoid Discriminatory Language
Be mindful of language that could offend or exclude users. Using inclusive and respectful terminology helps
create a positive first impression and a welcoming environment.
5. Include Practical Guides and Multimedia Elements
Go beyond static reference documentation by providing walkthroughs and step-by-step guides that help users
accomplish specific tasks. Incorporate multimedia like videos, GIFs, diagrams, and flowcharts to support
diverse learning styles.
6. Enable Interactivity in Documentation
Interactive elements such as "Try It" buttons for API calls allow developers to test functionality directly within
the docs, saving time and effort. This reduces the need to switch tools or piece together information manually.
7. Leverage Automated Documentation Tools
Use specification formats (e.g., OpenAPI) and code annotations to generate and keep documentation in sync
with code automatically. This reduces errors and maintenance overhead by connecting documentation with
the development lifecycle.
8. Ensure Accessibility
Design documentation to be usable by people with disabilities. For example, consider colorblindness when
choosing palettes, provide alt text for images, and use semantic markup for screen readers. Accessibility tools
can help identify potential issues.
9. Keep Content Up-to-Date
Regularly review and update documentation to reflect API changes. Outdated docs, screenshots, or tutorials
cause confusion and frustration. Treat documentation as an iterative process that evolves with the API.
10. Manage Content Bloat and Repetition
Periodically streamline content to remove clutter and redundancy. Avoid repeating the same concepts in
multiple places to maintain a concise and clear user experience.
11. Optimize Searchability and Relevance
When documenting multiple APIs or a large catalog, ensure users can easily find relevant information through
effective search and well-organized content structure.
12. Maintain Consistency Across Documentation
Use consistent style, tone, templates, and formatting across all API docs in an organization. This cohesion
supports a unified developer experience and reflects well on governance and quality standards.
13. Governance and Process
Establish processes and security measures for documentation creation, review, and maintenance to ensure
high quality at scale. Consistency and developer experience should be prioritized as the API ecosystem grows.