Gathering detailed insights and metrics for fastify-zod-openapi
Gathering detailed insights and metrics for fastify-zod-openapi
Gathering detailed insights and metrics for fastify-zod-openapi
Gathering detailed insights and metrics for fastify-zod-openapi
npm install fastify-zod-openapi
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
58 Stars
170 Commits
7 Forks
2 Watching
3 Branches
5 Contributors
Updated on 26 Nov 2024
TypeScript (99.09%)
JavaScript (0.91%)
Cumulative downloads
Total Downloads
Last day
-26.2%
2,055
Compared to previous day
Last week
19%
11,239
Compared to previous week
Last month
31.9%
40,971
Compared to previous month
Last year
4,188.1%
135,677
Compared to previous year
Fastify type provider, validation, serialization and @fastify/swagger support for zod-openapi.
Install via npm
, pnpm
or pnpm
:
1npm install zod zod-openapi fastify-zod-openapi 2## or 3pnpm add zod zod-openapi fastify-zod-openapi 4## or 5pnpm install zod-openapi fastify-zod-openapi
1import 'zod-openapi/extend'; 2import fastify from 'fastify'; 3import { 4 type FastifyZodOpenApiSchema, 5 type FastifyZodOpenApiTypeProvider, 6 serializerCompiler, 7 validatorCompiler, 8} from 'fastify-zod-openapi'; 9import { z } from 'zod'; 10 11const app = fastify(); 12 13app.setValidatorCompiler(validatorCompiler); 14app.setSerializerCompiler(serializerCompiler); 15 16app.withTypeProvider<FastifyZodOpenApiTypeProvider>().route({ 17 method: 'POST', 18 url: '/:jobId', 19 schema: { 20 body: z.object({ 21 jobId: z.string().openapi({ 22 description: 'Job ID', 23 example: '60002023', 24 }), 25 }), 26 response: { 27 201: z.object({ 28 jobId: z.string().openapi({ 29 description: 'Job ID', 30 example: '60002023', 31 }), 32 }), 33 }, 34 } satisfies FastifyZodOpenApiSchema, 35 handler: async (req, res) => { 36 await res.send({ jobId: req.body.jobId }); 37 }, 38}); 39 40await app.ready(); 41await app.listen({ port: 5000 });
1import 'zod-openapi/extend'; 2import { FastifyPluginAsyncZodOpenApi } from 'fastify-zod-openapi'; 3import { z } from 'zod'; 4 5const plugin: FastifyPluginAsyncZodOpenApi = async (fastify, _opts) => { 6 fastify.route({ 7 method: 'POST', 8 url: '/', 9 // Define your schema 10 schema: { 11 body: z.object({ 12 jobId: z.string().openapi({ 13 description: 'Job ID', 14 example: '60002023', 15 }), 16 }), 17 response: { 18 201: z.object({ 19 jobId: z.string().openapi({ 20 description: 'Job ID', 21 example: '60002023', 22 }), 23 }), 24 }, 25 } satisfies FastifyZodOpenApiSchema, 26 handler: async (req, res) => { 27 await res.send({ jobId: req.body.jobId }); 28 }, 29 }); 30}; 31 32app.register(plugin);
1import 'zod-openapi/extend'; 2import fastifySwagger from '@fastify/swagger'; 3import fastifySwaggerUI from '@fastify/swagger-ui'; 4import fastify from 'fastify'; 5import { 6 type FastifyZodOpenApiSchema, 7 type FastifyZodOpenApiTypeProvider, 8 fastifyZodOpenApiPlugin, 9 fastifyZodOpenApiTransform, 10 fastifyZodOpenApiTransformObject, 11 serializerCompiler, 12 validatorCompiler, 13} from 'fastify-zod-openapi'; 14import { z } from 'zod'; 15import { type ZodOpenApiVersion } from 'zod-openapi'; 16 17const app = fastify(); 18 19app.setValidatorCompiler(validatorCompiler); 20app.setSerializerCompiler(serializerCompiler); 21 22await app.register(fastifyZodOpenApiPlugin); 23await app.register(fastifySwagger, { 24 openapi: { 25 info: { 26 title: 'hello world', 27 version: '1.0.0', 28 }, 29 openapi: '3.0.3' satisfies ZodOpenApiVersion, // If this is not specified, it will default to 3.1.0 30 }, 31 transform: fastifyZodOpenApiTransform, 32 transformObject: fastifyZodOpenApiTransformObject, 33}); 34await app.register(fastifySwaggerUI, { 35 routePrefix: '/documentation', 36}); 37 38app.withTypeProvider<FastifyZodOpenApiTypeProvider>().route({ 39 method: 'POST', 40 url: '/', 41 schema: { 42 body: z.string().openapi({ 43 description: 'Job ID', 44 example: '60002023', 45 }), 46 response: { 47 201: { 48 content: { 49 'application/json': { 50 schema: z.object({ 51 jobId: z.string().openapi({ 52 description: 'Job ID', 53 example: '60002023', 54 }), 55 }), 56 }, 57 }, 58 }, 59 }, 60 } satisfies FastifyZodOpenApiSchema, 61 handler: async (_req, res) => 62 res.send({ 63 jobId: '60002023', 64 }), 65}); 66await app.ready(); 67await app.listen({ port: 5000 });
This library allows you to easily declare components. As an example:
1const title = z.string().openapi({ 2 description: 'Job title', 3 example: 'My job', 4 ref: 'jobTitle', // <- new field 5});
Wherever title
is used in your request/response schemas across your application, it will instead be created as a reference.
1{ "$ref": "#/components/schemas/jobTitle" }
For a further dive please follow the documentation here.
If you wish to declare the components manually you will need to do so via the plugin's options. You will also need to create a custom SerializerCompiler to make use of fast-json-stringify.
1const components: ZodOpenApiComponentsObject = { schemas: { mySchema } }; 2await app.register(fastifyZodOpenApiPlugin, { 3 components, 4}); 5 6const customSerializerCompiler = createSerializerCompiler({ 7 components, 8});
Alternatively, you can use JSON.stringify
instead.
1const customSerializerCompiler = createSerializerCompiler({ 2 stringify: JSON.stringify, 3});
Please note: the responses
, parameters
components do not appear to be supported by the @fastify/swagger
library.
If you wish to use CreateDocumentOptions, pass it in via the plugin options:
1await app.register(fastifyZodOpenApiPlugin, { 2 documentOpts: { 3 unionOneOf: true, 4 }, 5});
The default response serializer serializerCompiler
uses fast-json-stringify. Under the hood, the schema passed to the response is transformed using OpenAPI 3.1.0 and passed to fast-json-stringify
as a JSON Schema.
If are running into any compatibility issues or wish to restore the previous JSON.stringify
functionality, you can use the createSerializerCompiler
function.
1const customSerializerCompiler = createSerializerCompiler({ 2 stringify: JSON.stringify, 3});
By default, fastify-zod-openapi
emits request validation errors in a similar manner to fastify
when used in conjunction with it's native JSON Schema error handling.
As an example:
1{ 2 "code": "FST_ERR_VALIDATION", 3 "error": "Bad Request", 4 "message": "params/jobId Expected number, received string", 5 "statusCode": 400 6}
For responses, it will emit a 500 error along with a vague error which will protect your implementation details
1{ 2 "code": "FST_ERR_RESPONSE_SERIALIZATION", 3 "error": "Internal Server Error", 4 "message": "Response does not match the schema", 5 "statusCode": 500 6}
To customise this behaviour, you may follow the fastify error handling guidance.
This library throws a RequestValidationError
when a request fails to validate against your Zod Schemas
1fastify.setErrorHandler(function (error, request, reply) { 2 if (error.validation) { 3 const zodValidationErrors = error.validation.filter( 4 (err) => err instanceof RequestValidationError, 5 ); 6 const zodIssues = zodValidationErrors.map((err) => err.params.issue); 7 const originalError = zodValidationErrors?.[0]?.params.error; 8 return reply.status(422).send({ 9 zodIssues 10 originalError 11 }); 12 } 13});
1fastify.setSchemaErrorFormatter(function (errors, dataVar) { 2 let message = `${dataVar}:`; 3 for (const error of errors) { 4 if (error instanceof RequestValidationError) { 5 message += ` ${error.instancePath} ${error.keyword}`; 6 } 7 } 8 9 return new Error(message); 10}); 11 12// { 13// code: 'FST_ERR_VALIDATION', 14// error: 'Bad Request', 15// message: 'querystring: /jobId invalid_type', 16// statusCode: 400, 17// }
1app.withTypeProvider<FastifyZodOpenApiTypeProvider>().get( 2 '/', 3 { 4 schema: { 5 querystring: z.object({ 6 jobId: z.string().openapi({ 7 description: 'Job ID', 8 example: '60002023', 9 }), 10 }), 11 }, 12 attachValidation: true, 13 }, 14 (req, res) => { 15 if (req.validationError?.validation) { 16 const zodValidationErrors = req.validationError.validation.filter( 17 (err) => err instanceof RequestValidationError, 18 ); 19 console.error(zodValidationErrors); 20 } 21 22 return res.send(req.query); 23 }, 24);
1app.setErrorHandler((error, _req, res) => { 2 if (error instanceof ResponseSerializationError) { 3 return res.status(500).send({ 4 error: 'Bad response', 5 }); 6 } 7}); 8 9// { 10// error: 'Bad response'; 11// }
fastify-type-provider-zod: Big kudos to this library for lighting the way with how to create type providers, validators and serializers. fastify-zod-openapi is just an extension to this library whilst adding support for the functionality of zod-openapi.
1pnpm install 2pnpm build
1pnpm test
1# Fix issues 2pnpm format 3 4# Check for issues 5pnpm lint
To release a new version
🏷️ Choose a tag
, enter a version number. eg. v1.2.0
and click + Create new tag: vX.X.X on publish
.Generate release notes
button and adjust the description.Set as the latest release
box and click Publish release
. This will trigger the Release
workflow.Pull Requests
tab for a PR labelled Release vX.X.X
.Merge Pull Request
on that Pull Request to update main with the new package version.To release a new beta version
🏷️ Choose a tag
, enter a version number with a -beta.X
suffix eg. v1.2.0-beta.1
and click + Create new tag: vX.X.X-beta.X on publish
.Generate release notes
button and adjust the description.Set as a pre-release
box and click Publish release
. This will trigger the Prerelease
workflow.No vulnerabilities found.
No security vulnerabilities found.