What is OpenAPI? Examples, Purpose & Advantages
Tags: openapi, webdev, api, architecture
Published: 2023-02-22 13:37:40

[OpenAPI](https://swagger.io/specification/), previously known as "Swagger", is a specification for describing HTTP APIs. Since its initial release in 2011, it has become a commonly adopted tool for companies to generate documentation and client implementations for their endpoints.

In this post we will go over how it works, some examples, and the advantages (and disadvantages) of using it.

## The very basics

When you encounter an OpenAPI spec, it is either in JSON or Yaml format. I will look something like this condensed example from OpenAPI's own docs:

```jsonc
{
  "openapi": "3.0.0",
  "info": {
    "version": "1.0.0",
    "title": "Swagger Petstore",
    "license": {
      "name": "MIT"
    }
  },
  "servers": [{ "url": "http://petstore.swagger.io/v1" }],
  "paths": {
    "/pets": {
      "get": {
        "summary": "List all pets",
        /* Removed for brevity */
      },
      "post": {
        "summary": "Create a pet",
        /* Removed for brevity */
      }
    },
    "/pets/{petId}": {
      "get": {
        "summary": "Info for a specific pet",
        /* Removed for brevity */
    }
  }
}
```


What this example describes is a "PetStore" API. It is accessible at the domain `http://petstore.swagger.io/v1`, it is currently at version `1.0.0`, and it exposes 2 URL paths:

1. `/pets`
2. `/pets/{petId}`

The first path, `pets`, handles 2 different HTTP methods: `GET` and `POST`. The first lists all the available pets, and the second one creates a new pet (a very strange API, we will admit).

The second path only responds to the `GET` HTTP method, in which case it returns information about a _specific_ pet, and it expects the URL to include the _ID_ of the pet you are asking for.

For brevity, I have removed some details from this example. But you can see the the whole spec [here](https://github.com/OAI/OpenAPI-Specification/blob/36a3a67264cc1c4f1eff110cea3ebfe679435108/examples/v3.0/petstore.json). In it, you can see that the spec goes into detail about what the shape of the data it returns is, what errors can be occur, and much more.

This, in short is what OpenAPI is: a format for describing your API down to the smallest detail.

## What is it used for?

There are 2 main uses for using OpenAPI:

1. Documenting and communicating to your users how your API works
2. Automatically generating code that can interact with your API

### Documentation

Since an OpenAPI spec tells you exactly how your API works, we can use it to generate nice looking and easy to read documentation.

This is in fact what Doctave does - you can include your OpenAPI description and Doctave generates documentation automatically from your spec. Here is an example where [GitHub's OpenAPI spec](https://github.com/github/rest-api-description) is rendered in Doctave.

![Screenshot of GitHub's OpenAPI spec rendered in Doctave showing a the docs of a GET operation listing repositories starred by the authenticated user.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7twsgrza9qrqr6uqp0a2.png)

This can be incredibly useful for your colleagues that may be writing code against an API you have designed, or customers using your product.

There are a whole host of [OpenAPI tools](https://openapi.tools/) ranging from documentation to code generation to linting and validating your specs. It is worth browsing around to see what is out there.

### Generating API clients

In theory, if we have a well documented API, and know all the types in the responses as well as the available operations, we should be able to write a program that generates another program that can be used to interact with the API in question.

This is where the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator) tool comes in. It is able to generate client code in over 50 languages just by providing it an OpenAPI specification.

It goes even further and is able to generate _server stubs_ that you can use as a starting point for generating a compliant service implementing an API contract.

## Creating OpenAPI specifications

How does one go about creating an OpenAPI spec in the first place? How do you get that JSON or Yaml file that describes your API? You have two options:

1\. **Generate it automatically from your server code**

There are tools that will look at the code running on your server and create an OpenAPI file based on it. This can be a great way to get started.

2\. **Craft it by hand**

If you need more control, you can write the spec by hand. You don't have to do it all in your text editor though - there are visual and even collaborative tools for managing your OpenAPI specs.

There is no real right or wrong answer about which way is correct, but here are some arguments for and against both:

**Auto generation**

* ✅ Your spec will always be up to date
* ✅ Can sometimes require very little work from developers to set up
* ❌ It can be easy to accidentally introduce breaking changes

**Crafting by hand**

* ✅ Forces you to think carefully about API changes
* ❌ Can be more work (can be assisted by proper tooling)
* ❌ You have to ensure your server is compatible with your spec yourself

As a general rule, if you are descrbing an API that is consumed internally by others in your company, auto generating your specification can be a quick way to describe your API.

However if your customers are using your API, you need to be much more deliberate with breaking changes and API design over all. In this case, hand crafting your spec and running tests that ensure your service is compliant can be a better option.

## Advantages and disadvantages of OpenAPI

Communicating how your API works is a hard requirement for anyone to actually use it. This is the problem OpenAPI tries to solve.

The big benefit of OpenAPI is that _it is a standard_. There is a large set of tools that know the format and having an OpenAPI spec lets you and your users take advantage of those tools. Documentation, client generation, and much more become easier once you have a well specified API.

But as the saying goes, there is no free lunch. So what are some issues with OpenAPI that we should be aware or?

**1. Auto generation is not enough**

   You would be wrong to think that generating your OpenAPI spec from your server code is enough documentation for your users to get started.

   This is why many sections in the OpenAPI spec include a `description` field which according to the spec can include Markdown. The designers of OpenAPI understood that examples must have written guides and examples to make the spec useful and gave authors the ability to add written prose to guide their users.

   This means _you will have have to spend time adding explanations in your spec, even if you auto generate a lot of it._ This is less of an issue with OpenAPI itself, but something you should keep in mind.

**2. You need to provide _a lot_ of detail**

   It is easy to underestimate the amount of work that goes into describing your API. If you look at the screenshot above, the operation has a lot of detail: default values for parameters, example responses, a hand-written description.

   Doing this for _all_ of your operations is not a small task and you likely will not get the level of detail you need from just auto generating things from code. You will have to spend time annotating your code to give OpenAPI high quality hints about how your API works.

**3. Some languages are not well supported**

   If you are using a slightly more esoteric language, do not expect client code generation or producing OpenAPI specs from your servers to work flawlessly.

   Java, Go, Python, Ruby, JavaScript, and other "big" languages have well tested integrations, but your mileage may vary.

**4. Not a great fit for event-driven architectures**

   If your API uses asynchronous messages heavily, OpenAPI does not provide great primitives for describing them.

   Instead, you should consider looking into [AsyncAPI](https://www.asyncapi.com/), which grew out of OpenAPI to address this shortcoming.

Ultimately OpenAPI has proved itself to be a valuable tool by becoming the industry standard for describing HTTP APIs. It is a great tool that does its job very well when used correctly.