A Svelte library that auto-generates OpenAPI (Swagger) documentation for HTTP handlers in SvelteKit projects. This library scans your project’s routes to create a dynamic, accessible Swagger UI page that documents your API endpoints.
Install the package via npm:
npm install @obele-michael/swagger-ui-svelte
After installing the library, you can start using it by configuring your SvelteKit routes and initializing the OpenAPI generator.
Define HTTP method handlers (e.g., GET
, POST
) in your SvelteKit route files (+server.ts/js
or page.server.ts/js
). Here’s an example:
// src/routes/example/+server.ts
import type { RequestHandler } from './$types';
export const GET: RequestHandler = async () => {
return new Response(JSON.stringify({ message: 'Hello from GET!' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
};
export const POST: RequestHandler = async ({ request }) => {
const data = await request.json();
return new Response(JSON.stringify({ message: 'Received data', data }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
};
Run the OpenAPI generator script to scan your routes and create the openapi.json
file. The openapi.json
is generated in the static
folder of your project:
bun run generate:openapi
This command will create or update static/openapi.json
, documenting all detected endpoints in your project.
In your SvelteKit app, import and display Swagger UI using the provided component from @obele-michael/swagger-ui-svelte
:
<script lang="ts">
import { SwaggerUI } from '@obele-michael/swagger-ui-svelte';
</script>
<SwaggerUI url="/openapi.json" />
After setting up, visit your app to view the Swagger UI, which will render the documentation for your API endpoints based on openapi.json
.
GET
, POST
, PUT
, DELETE
, PATCH
, HEAD
, and OPTIONS
handlers in SvelteKit.Here’s a sample project structure to help illustrate the usage:
project-root/
├── src/
│ ├── lib/
│ │ ├── index.ts # Entry point for the library
│ │ ├── script/
│ │ │ └── generateOpenApi.ts # Script for OpenAPI generation
│ ├── routes/
│ │ ├── example/
│ │ │ └── +server.ts # Route file with HTTP handlers
│ └── app.svelte # Svelte app file
└── static/
└── openapi.json # Generated OpenAPI specification
Contributions, issues, and feature requests are welcome! Feel free to check out the issues page if you have any suggestions or run into problems.
This project is licensed under the MIT License.