Serverless OpenAPI Joi Plugin
Serverless plugin for creating OpenAPI v3 specifications with Joi validation.
This plugin allows you to define input validation for your serverless API endpoints and generates OpenAPI definitions from validation rules, which can be either saved somewhere or served directly as an endpoint in the API itself.
See full example project boilerplate here: anttiviljami/serverless-openapi-joi-boilerplate
Philosophy
As developers, we are lazy when it comes to writing documentation.
Even with nice modern tools like the OpenAPI standard (previously known as Swagger) which allows us to auto-generate API docs and clients from formatted specification documents, they are tideous to write and thus often out-of-date.
The best way to make sure API documentation stays up-to-date is to generate it from API code itself and actively use the generated API definition in our development workflows.
With serverless-openapi-joi, OpenAPI specification is generated as a by-product of defining Joi input validation rules to our API endpoints. As a bonus, we get nice machine- and human-readable Boomified validation errors.
Inspired by hapi-swagger
Example
Install the plugin:
npm install --save serverless-openapi-joi
In serverless.yml, add the plugin and define your api endpoints:
plugins: - serverless-openapi-joi functions: api: handler: index.handler events: - http: path: swagger.json method: get private: true - http: path: pets method: get private: true - http: path: pets/{id} method: get private: true - http: path: pets method: post private: true - http: path: pets/{id} method: patch private: true - http: path: pets/{id} method: delete private: true
In the handler:
; // ES6 syntax// or; // CommomJS syntax
;
Validation models are defined using Joi:
; ;
Routes define API operations using validation rules (see docs):
;
The OpenAPI specification for your API gets automatically generated and served at /swagger.json
!
You can also access the specification object anywhere programmatically using the
getSpecification()
method.
OpenAPI specifications can be easily viewed using tools like Swagger UI:
Documentation
View the documentation here: DOCS.md