Create an Express application for our simple API
FirstÂ letâ€™s create a simple Express application.
Running the above code launches an API server that exposes the following routes:
- GET /v1/pets
- POST /v1/pets
- GET /v1/pets/:id
Note:Â The APIs return values are contrived and not relevant to this tutorial.
Create an OpenAPI spec to describe our API
Now that we have written our simple API, letâ€™s add some validation. BUT, instead of writing a bunch of validation code, weâ€™ll describe our API by creating an OpenAPI 3 specification.
(Iâ€™ll assume you know how to create an OpenApi spec, hence Iâ€™ll describe only the relevant snippets. If youâ€™d like to see the full spec, goÂ here).
Letâ€™s make it a requirement that requests to GET /v1/pets must provide the query parameter,Â limit. Letâ€™s also require that limit be anÂ integerÂ with a valueÂ greater than zero.
Letâ€™s also make it a requirement that requests to POST /v1/pets must provide a JSON body containing a required field, name.
Weâ€™ll also add the NewPets component to our OpenAPI 3 spec.
Integrate automatic request validation with Express-OpenAPI-Validator
Finally, weâ€™ll make a few minor code adjustments to enable our API server to automatically validate API requests using our OpenAPI 3 specification.
The code adjustments include the following:
Require express-openapi-validatorâ€Šâ€”â€Ša package to automatically validate routes defined in Express against an OpenAPI 3 spec
- Install the OpenApiValidator onto our express application
- Provide an Express error handler to customize our error responses
- After making these changes, our final code is as follows:
(Note, steps 1, 2, and 3 indicating the new code thatâ€™s been added)
Start the server, thenâ€¦
Try it out
Letâ€™s execute some API requests withÂ curlÂ and observe the automatic request validation in action.
Letâ€™s tryÂ GET /v1/pets
Letâ€™s try POST /v1/pets
The full source code for this example can be foundÂ here.
If you dig express-openapi-validator,
StarÂ it on Github!