Finally a readable API Spec for both human and machine — OpenAPI (Swagger) Specification

Image for post
Image for post

Background

Problems

The below API is poorly written but it reflects what I had to deal with.

Image for post
Image for post

Perhaps you could argue that it’s just an issue with improper formatting and that if you choose the right template and with proper formatting like the example below, you could still have a clear API specification for others to integrate with.

Image for post
Image for post

But the below problems still persist:

  1. Inefficient and painstaking. It takes much manual effort to implement the API from these specs. It’s very tiring to go back and forth between your IDE and the browser.
  2. Inconsistency in formatting, there’s no universal standard and everyone has their own styles of writing them.
  3. Document and code not aligned. Because it’s manual there will be times when either the producer or the consumer’s code is not aligned with the document.
  4. Reduntancy. It’s repetitious to have your written code and a specification since your code is supposed to be the same as your specification.

OpenAPI to the rescue

This is what the OpenAPI generated documentation looks like:

Image for post
Image for post

As you can see all the API can be grouped and listed nicely in the Swagger UI.

Image for post
Image for post

If you expand any of the API you will be able to see the details for each API, what the request needs (whether request json, query params, or headers) and what the sample response will be. There’s also a “Try it out” button where you can actually send a real request to this API.

Image for post
Image for post

After you click the “Try it out” button, you can enter into the required parameters on the UI and when you click “Execute”, it’ll generate a curl statement for you and depending on your setup you can actually send the request out to the specified URL.

Image for post
Image for post

Of course in this case I’m just testing a random API so I have a 500 in response but I think you get the point.

Try it out with online editor

Image for post
Image for post

There are many OpenAPI samples on the internet for you to reference on.

Contract First Approach

It’s a contract afterall

In the next post I’ll walk you through on how to use the OpenAPI Yaml spec to generate the code stub for both consumers and producers.

https://theochiu2010.medium.com/step-by-step-openapi-swagger-setup-6902ff93efbe

Written by

Just another developer who's into lazy tools that can make my life easier, and hopefully yours too.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store