DEV Community

Cover image for Automate Your API Documentation with sveltekit-api-gen
Michael Amachree
Michael Amachree Subscriber

Posted on

Automate Your API Documentation with sveltekit-api-gen

Documentation is often the part of development that gets left behind. We all know we should write it, but keeping an OpenAPI spec in sync with your code can be tedious.

If you are building a backend with SvelteKit, sveltekit-api-gen is here to save the day.

The big idea is simple: treat your endpoint implementation files as the source of truth, and generate everything else from there.

What is it?

sveltekit-api-gen is a tool that automatically generates OpenAPI 3.0 specifications from your SvelteKit server endpoints. It does this by parsing JSDoc @swagger annotations directly in your code.

How it Works

Instead of writing a separate YAML or JSON file for your API spec, you simply annotate your implementation files.

// src/routes/api/users/+server.ts

/**
 * @swagger
 * /api/users:
 *   get:
 *     description: Get all users
 *     responses:
 *       200:
 *         description: A list of users
 */
export async function GET() {
  // ... your logic
}
Enter fullscreen mode Exit fullscreen mode

sveltekit-api-gen scans these comments and builds a complete, compliant OpenAPI specification for you.

A practical workflow

Here’s a lightweight workflow that keeps teams honest without adding a lot of process:

  1. Add @swagger docs as you build endpoints.
  2. Generate openapi.json (or openapi.yaml) in CI.
  3. Publish it to Swagger UI, Postman, or your internal docs site.
  4. Fail CI if generation breaks (so docs drift is caught immediately).

Key Benefits

  1. Single Source of Truth: Your documentation lives right next to your code. If you change the code, you update the comment right above it.
  2. Automation: No more manual updates to huge JSON files.
  3. Standard Compliant: Generates standard OpenAPI 3.0 specs, compatible with Swagger UI, Postman, and other tools.

Tips and gotchas

  • Be consistent with paths: make sure the documented path matches your SvelteKit route layout.
  • Document error responses: even a simple 400 and 500 section saves debugging time.
  • Keep schemas close: if you’re using Zod or similar, consider mirroring the important constraints in your swagger docs.

Get Started

Check out the repository on GitHub: https://github.com/Michael-Obele/sveltekit-api-gen

Install the package:

npm install -D sveltekit-openapi-generator
# or
pnpm add -D sveltekit-openapi-generator
# or
bun add -d sveltekit-openapi-generator

Once installed, check the repo README for the exact generate command and output path you prefer (that part is intentionally configurable).
Enter fullscreen mode Exit fullscreen mode

If you found this helpful, please star the repo and share the post!

Top comments (0)