The main goal of this project is to provide type-safety for SvelteKit's API endpoints which can be defined in +server.ts
files. This project will generate an OpenAPI schema from your API endpoints and provide a Swagger UI to explore your API. It will also generate a type-safe client library for your API. This is achieved by using a Vite plugin.
This project is still in the early stages of development. It is not yet ready for production use. Please feel free to contribute!
The inspiration for this project came from my codebase increasingly relying on SvelteKit's API endpoints for fetching mostly JSON data. Similar to SvelteKit's PageData
for load
functions, I wanted "automatic" type safety for my API endpoints. In addition, as my codebase grows in size, I wanted to use Swagger UI to explore my API endpoints without manually defining an OpenAPI schema.
This project is a Vite plugin because it needs to be able to parse your SvelteKit API endpoints. Once an OpenAPI schema is generated, a Swagger UI is served - this is made possible by using the configureServer
hook provided by the Vite Plugin API.
A vite plugin is used to generate the OpenAPI schema and client library. The plugin will also serve the Swagger UI.
npm create svelte@latest
+server.ts
files in your SvelteKit projectInstall the plugin
npm install --save-dev vite-plugin-sveltekit-api-generator
Add the plugin to your vite.config.ts
file
import { defineConfig } from 'vite';
import { sveltekit } from '@sveltejs/kit/vite';
import sveltekitApiGenerator from 'vite-plugin-sveltekit-api-generator';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [sveltekit(), sveltekitApiGenerator()],
});
Upon running npm run dev
, the vite plugin will:
+server.ts
files, and serve it at http://localhost:5173/swagger-ui.json
src/lib/api.ts
http://localhost:5173/swagger-ui
Only endpoints that make use of SvelteKit's json()
helper function will have type safety for the response body. For example, the following endpoint will have type safety for the response body:
export async function GET({ params }) {
const { id } = params;
const user: {
id: number;
name: string;
} = await getUser(id);
return json(data);
}
If you do not use the json()
helper function, the response will be typed as any
.
If you use url.searchParams.get()
or url.searchParams.getAll()
, the OpenAPI schema will include query parameters.
request.formData()
and request.json()
usageSee the open issues for a full list of proposed features (and known issues).
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
Distributed under the MIT License. See LICENSE.txt
for more information.