In the previous post, I went on a small spike to explore generating TypeScript types from valid JSON schemas. Now, I want to look a little deeper at OpenAPI Schema validation.
This example will build a little more on top of the previous post, however, it is not required reading.
In a Yarn or NPM project directory, install the following:
We are also going to add in a few of the pieces I wrote for the Book schema in the previous post, so create
book.json and add the following:
The above is actually a little different to what I had in the previous blog posts, so make sure you do copy it across.
We are going to import this in and using it for our values for a component.
Creating the Open Specification
I am awaiting the release of the OpenAPI 3.1 spec as it is the culmination of a huge effort to align the latest JSON Schema draft and the OpenAPI specification, but for now, we will run with 3.0.3.
OpenAPI can be written in YAML or JSON, so, for now, we will keep things as JSON.
Basically I just copied across the example they gave for using components and transformed it from YAML to JSON. Then I made some adjustments to check for a path
/books where the GET request expects back an array of type Books.
Setting Up The Validator
Add the following to
The most confusing part here may be where I am adjusting the Open API Schema to use the definitions from
book.json. I am doing this is keep in line with what I was doing with combining the other JSON files. I am thinking in my own work that I may follow the precedent of splitting up component definitions and combining when required.
Running The Validator
node index.js. If nothing happens, then perfect!
If you want to test the validity is doing what it needs, adjust a value in
openapi.json and see what happens.
"description": "A list of books", into
"descriptions": "A list of books",. Running the file again will give us the following logged out:
Success! Now we have a way to validate our OpenAPI schema.
Resources and Further Reading
Image credit: Markos Mant
Originally posted on my blog.