0.2.2 • Published 7 months ago

@deboxsoft/sveltekit-openapi v0.2.2

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Table Of Contents

Installation

npm install sveltekit-openapi
yarn add sveltekit-openapi
pnpm add sveltekit-openapi

Usage

defineAPI() / new API()

Use defineAPI or new API to declare a new API object. This object is the main entry point for declaring your API routes.

const myAPI = defineAPI({
	info: {
		title: "My API",
		description: "My API Description",
		version: "0.0.1",
	},
	servers: [{ url: "http://localhost:5173" }],
})

API.defineEndpoint()

Use API.defineEndpoint() to define a new endpoint. This is used as a SvelteKit Request Handler and is called whenever a request is made to the endpoint. Provided parameters are automatically validated against the provided Zod schemas.

export const POST = myAPI.defineEndpoint({
  operationId: "createUser",
  summary: "Create a new user",
  parameters: {
    query: z.object({
      my_query_param: z.string().optional(),
    }),
    path: z.object({
      my_path_param: z.string().optional(),
    }),
  }
  requestBody: z.object({
    name: z.string().min(3),
    age: z.number(),
  }),
  // Only the responses object is required
  responses: {
    201: {
      content: z.object({
        user: z.object({
          id: z.string(),
          name: z.string(),
          age: z.number(),
        })
      })
    },
  }
}, ({ params, json }) => {
  // The params object is stictly typed based on the provided parameters schema
  // In this case, it would be:
  // { query: { my_query_param: string | undefined }, path: { my_path_param: string | undefined }, body: { name: string, age: number } }
  console.log(params.query.my_query_param)
  console.log(params.path.my_path_param)

  // The provided json function is a strictly typed version of SvelteKit's json function
  // It automatically validates the provided object against the response schema
  return json(201, {
    user: {
      id: "123",
      ...params.body,
    }
  })
})

API.generateSpec()

Generates an OpenAPI specification object based on the defined endpoints. Often used in conjunction with a SvelteKit endpoint to serve the specification.

// `src/routes/api/openapi.json/+server.ts`
import { json, type RequestHandler } from "@sveltejs/kit"

import { myAPI } from "$lib/server/api"

// Serve our OpenAPI specification at `/api/openapi.json`
export const GET: RequestHandler = async () => {
	const myAPISpec = await myAPI.generateSpec()
	return json(myAPISpec)
}

SwaggerUI Component

A swagger-ui wrapper component is provided to easily render the OpenAPI specification in a SvelteKit route.

<script lang="ts">
	import { SwaggerUI } from "sveltekit-openapi/ui"
</script>

<SwaggerUI url="/api/openapi.json" />

Examples

0.2.2

7 months ago