fastify-openapi-validator
v4.12.0-beta.3
Published
Automatically validate API requests with OpenAPI 3 and Fastify.
Downloads
8
Maintainers
Readme
🦋 fastify-openapi-validator
An OpenApi validator for Fastify that automatically validates API _requests using an OpenAPI 3 specification.
Install
npm install [email protected]
Usage
Code
const OpenApiValidator = require('fastify-openapi-validator');
app.use(
OpenApiValidator.middleware({
apiSpec: './openapi.yml',
// additional options
}),
);
Options
{
apiSpec: OpenAPIV3.Document | string;
validateRequests?: boolean | ValidateRequestOpts;
validateSecurity?: boolean | ValidateSecurityOpts;
ignorePaths?: RegExp | Function;
coerceTypes?: boolean | 'array';
unknownFormats?: true | string[] | 'ignore';
formats?: Format[];
$refParser?: {
mode: 'bundle' | 'dereference';
};
validateFormats?: false | 'fast' | 'full';
}
See detailed documentation
Note: some options including validateResponses
, operationHandlers
are not yet supported for Fastify
Example
// 1. require the module
const openApiValidator = require('fastify-openapi-validator');
const { Pets } = require('./services');
const pets = new Pets();
function plugin(instance, options, next) {
// 2. configure the validator (see options)
instance.register(openApiValidator, {
apiSpec: './openapi.yml',
});
// 3. define routes
instance.get('/v1/pets', (request, reply) => {
return pets.findAll(request.query);
});
instance.get('/v1/pets/:id', (request, reply) => {
const pet = pets.findById(request.params.id);
if (!pet) reply.code(404).send({ msg: 'not found' });
return pet;
});
// 4. set an error handler and error shape
instance.setErrorHandler(function (error, request, reply) {
const code = error.status ?? 500;
const errors = error.errors;
const message = error.message;
reply.code(code).send({
message,
errors,
});
});
next();
}
module.exports = plugin;
Related Projects
License
MIT