OpenAPI Module ๐
OpenAPI allows you to create a json in openapi "3.0" or "3.1" format, compatible with tools like swagger, postman and anyone that receives the openapi format.
Note ๐ฆ: rocket-kit uses the openapi3-ts package.
To define the openapi version you must use the oas attribute in the kit configuration object.
// "path file" ~ ./utils/rocketKit
import { createRocket } from "next-rocket-kit";
export const { Http, OpenApi } = createRocket();
OpenAPI Exampleโ
// "path file" ~ ./utils/rocketKit
import { createRocket } from "next-rocket-kit";
export const rocket = createRocket();
export const { Http, OpenApi } = rocket;
import { OpenApi } from "./utils/rocketkt";
// declare info and openapi version.
const openApi = OpenApi({
openapi: "3.0.3", // or 3.1.0
info: {
title: "example",
description: "string",
termsOfService: "string",
contact: {
name: "Author",
},
license: {
name: "MIT",
},
version: "1.0.0",
},
});
openApi.addSchema("User", {
type: "object",
properties: {
id: {
type: "string",
},
name: {
type: "string",
},
},
});
openApi.addPath("/items", {
description: "return item list",
post: {
description: "get items",
summary: "get items",
requestBody: {
description: "body",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/User" },
},
},
},
responses: {
200: {
description: "ok",
content: {
"application/json": {
schema: {
type: "object",
properties: {
id: {
type: "string",
},
},
},
},
},
},
},
},
});
// return json string
openApi.getSpecAsJson();
// or return yml stirng
openApi.getSpecAsYaml();
Recommendations for use with third-party packages to OpenAPIโ
How use OpenAPI with "zod".
- @anatine/zod-openapi: With this package we can reuse the "zod" validation schemas that you should already be using in the Route schema field to validate the body or some other field of the request.
import { OpenApi } from "@/utils/rocketKit";
import { generateSchema, extendZodWithOpenApi } from "@anatine/zod-openapi";
import { z } from "zod";
// extend zod
extendZodWithOpenApi(z);
// declare info and openapi version.
const openApi = OpenApi({
openapi: "3.0.3", // or 3.1.0
info: {
title: "example",
description: "string",
termsOfService: "string",
version: "1.0.0",
contact: {
name: "Author",
},
license: {
name: "MIT",
},
},
});
const ItemZodSchema = z
.object({
id: z.string().uuid().nonempty().openapi({
title: "Item ID",
description: "A UUID generated by the server",
}),
name: z.string().min(2),
})
.openapi({
title: "Item",
description: "A item schema",
});
const ItemOpenAPiSchema = generateSchema(ItemZodSchema);
openApi.addSchema("Item", ItemOpenAPiSchema);
Note ๐งช: In the case of Yup we have not found a package that meets the standards we are looking for, we remain attentive to options proposed by the community.