I always found the hardest thing about API work was the documentation.

Sure, there are loads of nice tools out there to help you define it, provide nice front-ends and the like, but maintaining that isn’t anywhere nearly as fun as getting the actual work done. So soon enough, you’ve got stale documentation with little errors, and validation rules that don’t quite match up.

A recent NodeJS API project came my way which had out-of-date OpenAPI 3 documentation for the few endpoints it already had, but the understanding that we where going to start using it a lot more, so it needed to get up to scratch.

OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs

I figured that if we where going to maintain this OpenAPI spec, which contained all the validation rules for the endpoints, then there must be a way we could use that to save us some time.

What if we could use that spec to enforce the validation? What if we could use it as the basis of the endpoint testing?

If we could get these two things, we have the wonderful combo of the OpenAPI spec needing to be write for the validation to work, and the validation being unable to deviate from the spec — so no more dodgy documentation where that param is documented as an int but it’s actually a float..

.. and if we can build tests based from the documentation then all our outputs have to be as defined, so the consumers of the API don’t get urked if we send an object and they’re expecting an array.

Using the OpenAPI spec to enforce the validation and be the crux of the tests enforces good definition of the API and removes all the nasty little ‘Ohh yea, that only returns X if Y’ that plagues API development IMHO.

So let’s stop waffling here and create something simple to prove how this works.