To build API documentation with Astro, write your guides in Markdown, generate one reference page per endpoint from your OpenAPI file using a content collection, render request and response examples with Astro’s built-in syntax highlighting, and deploy the static output. The result is fast, searchable API documentation that stays in sync with your spec because the reference pages are built from it on every deploy.
This guide covers two routes to API documentation in Astro: Starlight with a community OpenAPI plugin, and a custom build where you control every page. Both produce static HTML that any host can serve.
Key Takeaways
- Good API docs have three layers: a quickstart, task guides, and a complete endpoint reference.
- Generate the reference from your OpenAPI spec so it can’t drift from the real API.
- Astro’s
file()loader accepts a customparser, which is enough to turn an OpenAPI file into one entry per operation.- Show working request examples in more than one language and a real response for each endpoint.
- Starlight is the fastest start; a custom Astro site is better when docs must match a product site.
What developers need from API documentation
Developers judge an API by how fast they get a first successful request. Structure the docs around that:
| Section | Purpose |
|---|---|
| Quickstart | Get an API key and make one working call in under five minutes |
| Authentication | Key types, headers, scopes, rotating keys |
| Guides | Task-based walkthroughs: “Create a customer”, “Handle webhooks” |
| API reference | Every endpoint: method, path, parameters, request body, responses, errors |
| Errors | Error codes with causes and fixes |
| Changelog | Breaking and non-breaking changes with dates |
| SDKs | Install commands and links per language |
The reference is the part people return to most, and it’s the part most likely to go stale when written by hand. That’s why the build below generates it.
Option 1: Starlight with an OpenAPI plugin
Starlight is Astro’s official documentation framework. It gives you a sidebar, search, dark mode, and accessible navigation out of the box.
# Terminal
npm create astro@latest -- --template starlight api-docs
cd api-docs
npm run dev
Write guides as Markdown or MDX in src/content/docs/. For the reference, community plugins such as starlight-openapi read an OpenAPI file and generate the endpoint pages inside Starlight’s layout. The Starlight plugins guide lists options and how to add them, and Astro or Starlight for docs helps you decide between the two routes.
Choose Starlight when your docs can live on their own subdomain with a standard docs look. Choose the custom route below when you need your own design, a product-specific landing page, or full control over how each endpoint renders.
Option 2: Generate reference pages from OpenAPI
The custom route uses a content collection whose entries are API operations. Astro’s built-in file() loader takes an optional parser function, so you can read your OpenAPI JSON and return one object per operation.
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob, file } from 'astro/loaders';
import { z } from 'astro/zod';
const METHODS = ['get', 'post', 'put', 'patch', 'delete'];
const operations = defineCollection({
loader: file('openapi.json', {
parser: (text) => {
const spec = JSON.parse(text);
return Object.entries(spec.paths).flatMap(([path, item]) =>
Object.entries(item)
.filter(([method]) => METHODS.includes(method))
.map(([method, op]) => ({
id: op.operationId,
method: method.toUpperCase(),
path,
summary: op.summary ?? '',
description: op.description ?? '',
tag: op.tags?.[0] ?? 'General',
parameters: op.parameters ?? [],
responses: op.responses ?? {},
})),
);
},
}),
schema: z.object({
method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']),
path: z.string(),
summary: z.string(),
description: z.string(),
tag: z.string(),
parameters: z.array(z.object({
name: z.string(),
in: z.string(),
required: z.boolean().optional(),
description: z.string().optional(),
})),
responses: z.record(z.string(), z.any()),
}),
});
const guides = defineCollection({
loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/guides' }),
schema: z.object({ title: z.string(), description: z.string(), order: z.number() }),
});
export const collections = { operations, guides };
Every operation in your spec now needs an operationId, which is good practice anyway because SDK generators use it too. If the spec is YAML, use a YAML parser in the same function. When the spec changes, the next build picks it up, and the schema fails the build if a required field is missing. The content layer loaders guide covers custom loaders if you later want to fetch the spec from a URL.
The endpoint page
Each operation becomes a page under /reference/. Astro’s <Code /> component highlights examples at build time with Shiki, so no syntax highlighting JavaScript ships to the browser.
---
// src/pages/reference/[id].astro
import { getCollection } from 'astro:content';
import { Code } from 'astro:components';
import DocsLayout from '../../layouts/DocsLayout.astro';
export async function getStaticPaths() {
const ops = await getCollection('operations');
return ops.map((op) => ({ params: { id: op.id }, props: { op } }));
}
const { op } = Astro.props;
const { method, path, summary, description, parameters, responses } = op.data;
const base = 'https://api.example.com/v1';
const curl = `curl -X ${method} ${base}${path} \\
-H "Authorization: Bearer $API_KEY"`;
const js = `const res = await fetch('${base}${path}', {
method: '${method}',
headers: { Authorization: \`Bearer \${process.env.API_KEY}\` },
});
const data = await res.json();`;
const example = responses['200']?.content?.['application/json']?.example;
---
<DocsLayout title={`${method} ${path}`} description={summary}>
<h1>{summary}</h1>
<p class="endpoint"><span class={`method ${method.toLowerCase()}`}>{method}</span> <code>{path}</code></p>
<p>{description}</p>
{parameters.length > 0 && (
<>
<h2>Parameters</h2>
<table>
<thead><tr><th>Name</th><th>In</th><th>Required</th><th>Description</th></tr></thead>
<tbody>
{parameters.map((p) => (
<tr><td><code>{p.name}</code></td><td>{p.in}</td><td>{p.required ? 'Yes' : 'No'}</td><td>{p.description}</td></tr>
))}
</tbody>
</table>
</>
)}
<h2>Request</h2>
<Code code={curl} lang="bash" />
<Code code={js} lang="js" />
{example && (
<>
<h2>Response</h2>
<Code code={JSON.stringify(example, null, 2)} lang="json" />
</>
)}
</DocsLayout>
Include a real example response in your OpenAPI spec for every endpoint. A reference page without one forces developers to make a call just to see the shape of the data. The Shiki syntax highlighting guide covers themes and line highlighting, and a copy code button is a small addition developers notice immediately.
Sidebar grouped by tag
OpenAPI tags map naturally onto sidebar groups. Build the sidebar once from the same collection so new endpoints appear without editing navigation by hand.
---
// src/components/ReferenceNav.astro
import { getCollection } from 'astro:content';
const ops = await getCollection('operations');
const groups = Object.groupBy(ops, (op) => op.data.tag);
const current = Astro.url.pathname;
---
<nav aria-label="API reference">
{Object.entries(groups).map(([tag, items]) => (
<details open>
<summary>{tag}</summary>
<ul>
{items.map((op) => {
const href = `/reference/${op.id}/`;
return (
<li>
<a href={href} aria-current={current === href ? 'page' : undefined}>
<span class={`method ${op.data.method.toLowerCase()}`}>{op.data.method}</span> {op.data.summary}
</a>
</li>
);
})}
</ul>
</details>
))}
</nav>
Native <details> elements give you collapsible groups with no JavaScript. Object.groupBy is available in current Node.js versions that Astro 7 supports.
Guides, quickstart and errors
Reference pages tell developers what exists; guides tell them how to get something done. Write guides in MDX so you can drop in tabs or callouts where needed, and keep each one focused on a single outcome.
A good quickstart has four steps: create an account and key, install an SDK or use curl, make one request, and read the response. Test it on a clean machine before every major release. The errors page deserves the same care: list each code with its HTTP status, what causes it, and how to fix it, because that’s the page developers search for at 2 a.m.
If you prefer a ready-made design, the Astro documentation themes category includes Calaix, built to document code and API integrations, and Docket, a lightweight docs template for small and medium products. On the free side, Starlight is the standard choice, and Astro’s official starters are a clean base for a custom build.
Search, versioning and deployment
Add Pagefind for search: run pagefind --site dist after astro build and load its UI on docs pages. Because endpoint summaries and parameter names are in the HTML, developers can search for customer_id and land on the right endpoint. The Pagefind guide shows the setup.
For versioning, the simplest approach is one build per major version (/v1/, /v2/), each from its own spec file and branch. Most APIs only need the current version plus the previous one documented.
Deploy dist/ to Cloudflare Pages, Netlify, Vercel or GitHub Pages; our static deployment docs cover each. Then add a CI step that rebuilds the docs whenever openapi.json changes, so the reference ships with the API. See the official Astro content loader reference and the OpenAPI Specification for details on both sides.
FAQ
Can Astro generate API documentation from an OpenAPI spec?
Yes. You can pass a custom parser to Astro’s file() loader that reads your OpenAPI file and returns one entry per operation, then generate a page per entry with getStaticPaths(). Starlight users can also use community plugins that generate the reference pages for them.
Is Starlight good for API documentation?
Starlight is a strong choice for API docs that suit a standard documentation layout. It includes search, sidebar navigation, dark mode and accessibility features, and community plugins add OpenAPI reference pages. Use a custom Astro site if you need a fully bespoke design.
How do I keep API docs in sync with the API?
Generate the reference pages from the same OpenAPI file your API uses, and rebuild the docs in CI whenever that file changes. A Zod schema on the collection fails the build if an operation is missing required fields such as a summary or method.
Do Astro API docs need JavaScript?
No. Syntax highlighting with Astro’s <Code /> component happens at build time, collapsible navigation can use native <details> elements, and Pagefind’s search loads a small script only where you add it. An “API playground” that sends live requests would need a client-side island.
Where should I host API documentation built with Astro?
Any static host works, since the output is plain HTML, CSS and assets. Cloudflare Pages, Netlify, Vercel and GitHub Pages all serve Astro builds well and can rebuild automatically when you push changes to the spec or guides.