# OpenAPI Specification

## Summary


Services and applications expose interfaces that we call APIs. Every service can define its APIs in any way it wants provided those APIs are properly documented. However, there are benefits in following a standard to define or describe an API. This is exactly where the OpenAPI Specification (OAS) becomes relevant. 

OAS defines the rules, syntax and semantics for describing a RESTful API. OAS is language-agnostic, that is, it can be used for writing code in any programming language. It's in a format that can be read by both humans and machines. It's self-contained: no additional source code or documentation is required to understand an API specified in OAS. 

OAS is vendor-neutral and maintained by the *OpenAPI Initiative (OAI)* under the Linux Foundation. The specification document uses Apache License V2.0.

## Discussion

### What are the benefits of adopting the OpenAPI Specification?

OAS enables higher efficiency, better collaboration, stable implementation and faster time to market. It makes APIs reusable and maintainable. More people can understand an OAS-based API definition since OAS provides a common vocabulary. Multiple teams can work in parallel since OAS enables a shared understanding of the APIs. Downstream service integration, continuous delivery and application security are further areas improved by OAS. 

Because OAS is machine-readable, many tools exist to automatically validate, implement, test, mock or document APIs. Errors can be caught early even before any code is written. Moreover, client and server implementations can be generated automatically. This is commonly called the **API-first** approach whereby APIs are defined first. This is contrary to the traditional code-first approach. 

JSON Schema can describe only the data model. OAS can describe the entire API while also being compatible with JSON Schema. 

OAS is openly developed and released under an open license. It has wide industry support with more than 40 members at the OAI. It's got good documentation and support. 


### Could you share some case studies of OpenAPI?

Two places where OAS has become important are eCommerce platforms (eg. eBay) and the media industry (eg. Twitter). This has led to faster innovation. In banking, OAS has improved API security. At eBay, a transformer service enabled their customers to migrate from legacy contracts to OpenAPI contracts. 

One eCommerce company migrated from a monolithic to a microservices architecture. OAS enabled them to generate API mocks from the API specifications and conduct many API acceptance tests. As a result, fewer end-to-end tests sufficed. In another company, API mocks served as reference for real implementations. 

OAS integrates with and helps in CI/CD pipelines. For example, changes to the API specification can be automatically validated using GitHub Actions. If the validation succeeds, the pull request can be automatically merged. 

An API specification in OAS can be defined by someone and implemented by someone else. For example, 3GPP defined the 5G Core Network APIs using OAS. These APIs will then be implemented by various industry vendors. Network elements can come from different vendors and yet interwork more easily. Off-the-shelf tools have been used to test implementations and discover vulnerabilities. 


### Could you give a technical overview of the OpenAPI Specification?

An **OpenAPI Document** can be in either JSON or YAML format. If an API is specified in multiple files, it's recommended that the root file is named `openapi.json` or `openapi.yaml`. 

The document has a hierarchical structure starting from a root object called **OpenAPI Object**. Fields of this object are `openapi`, `info`, `jsonSchemaDialect`, `servers`, `paths`, `webhooks`, `components`, `security`, `tags` and `externalDocs`. At least one of `paths`, `components` or `webhooks` must be present. All field names (at the root level or otherwise) are case sensitive unless otherwise stated. Fields are either fixed or patterned with regex. At any level, the specification can be extended with a patterned field that starts with `x-`. 

**Data types** in OAS are based on JSON Schema Specification. Examples include `integer`, `number` and `string`. OAS extends some of these with additional formats. Where `description` field is used, it can be formatted with CommonMark markdown. 


### Could you describe the root-level fields of the OpenAPI Specification?

We describe briefly the following root-level fields: 

    + `openapi`: Specifies the OAS version number. This is a string of the form *major.minor.patch*.
    + `info`: Contains metadata on the API. Its fields include `title`, `summary`, `description`, `termsOfService`, `license`, etc.
    + `jsonSchemaDialect`: Sets the default dialect such as JSON Schema 2020-12.
    + `servers`: One or more Server Objects, each containing at least a URL. If omitted, defaults to a Server Object with URL `/`.
    + `paths`: One or more Path Objects. Each Path Object represents an API endpoint along with operations permitted on it.
    + `webhooks`: Webhooks are called by the API provider and may be implement by the consumer.
    + `components`: Contains all reusable objects. Definitions here are generally referenced (using `$ref`) elsewhere in the document.
    + `security`: Specifies security mechanisms across the API but individual operations can override this. Reuses `securitySchemes` from Components Object.
    + `tags`: Tags provide a way to organize operations on endpoints. Operations may be defined without tags or use tags not defined at the root level.
    + `externalDocs`: One or more URLs to external documentation.

### How can API endpoints be specified in OpenAPI?

In OAS, API endpoints are called **Paths**. Each Path Object is an endpoint and must start with `/` character. This is appended to a server URL to obtain a full endpoint URL. RESTful HTTP methods (get, post, delete, etc.) are defined as Operation Objects within a Path Item Object.  

Each **Operation Object** has the field `operationId` that's case sensitive and must be unique. The Operation Object also includes `requestBody` that conforms to HTTP 1.1 specification RFC7231. The field `responses` includes a list of possible responses to the operation's request.  

A **Response Object** is associated with an HTTP status code (200, 404, etc.) or `default`. A `200` status response is usually accompanied by the `content` field that can define multiple Media Type Objects. For example, the API can define response content for both `application/json` and `application/xml`. The `description` field of a Response Object is mandatory and is meant to give API consumers a useful message to complement the HTTP status code.  


### What tools are available within the OpenAPI ecosystem?

The company SmartBear continues to market products under the name of *Swagger*. Its online Swagger Editor is a useful tool to write API specification. It comes with an example called *Petstore*. The editor validates the specification and updates the documentation almost in real time. Developers can make API calls from the browser provided there's a hosted server implementation of the API. The editor's menu also has links to generate client and server code. 

OpenAPI.Tools has a curated list of many tools that work with OAS. There are tools that take code and generate OAS; turn OAS into client SDKs, server or mock server implementations; generate documentation; validate data; exercise requests and validate the responses; offer user-friendly GUIs for editing/viewing OAS; and more. If writing in JSON or YAML is not preferred, Domain-Specific Languages (DSLs) are also available. CUE is an example. 

The OAI maintains another list of OpenAPI tools.


### What are some best practices when using OpenAPI?

Beyond OpenAPI, many of the best practices we mention here are applicable for general API design. Developers should adopt an **API-first approach** rather than code-first approach. This helps multiple teams to work in parallel and efficiently, particularly when their apps are composed of microservices. 

Both producers and consumers must get involved. In fact, APIs should be **consumer-driven** rather than producers defining them from just the data model. This can be extended to consumer-driven contract testing. This can catch breaking changes early. 

Adopt a **style guide** for your APIs. This could describe the naming convention such as using lowercase for server URLs or kebab-case for paths. This could prohibit using HTTP method names in paths. In any case, all these rules can be specified formally and used during validation. 

Beginners can **study OpenAPI examples** published by well-known organizations. Publicly shared OpenAPI documents from SendGrid and GitHub are worth studying. 


### What are some limitations or criticisms of OpenAPI?

In November 2021, four years after OAS 3.0's release, it was observed that many APIs were still using Swagger 2.0. Many tools that supported Swagger 2.0 have not migrated to the newer specification. This has led developers to continue with the older specification. The name change has also caused confusion. Swagger UI still exists and its only the Swagger Specification that has become OAS. 

OAS requires some learning curve and adjustments to workflows. For example, end-to-end testing must make way to consumer-driven contract testing. In one case study, many developers in the team didn't understand the new workflows even 12 months after the change. 

There's a danger that developers might treat OAS as a magic bullet. OAS is not a shortcut to understanding an API. Techniques such as design thinking and domain-driven design are still relevant in creating great APIs.

## Milestones

Aug  
2011

**Swagger 1.0** is released. Tony Tam started working on Swagger back in 2010 while at Wordnik. 

Sep  
2014

**Swagger 2.0** is released. 

Mar  
2015

SmartBear Software acquires the Swagger Specification. 

Nov  
2015

SmartBear and a few other companies announce the formation of the **OpenAPI Initiative (OAI)**. It's formed as an open source project under the Linux Foundation. In December, the Swagger Specification is donated to the OAI. The idea is to standardize and bring formalism to how APIs are described. While Swagger, RAML and API Blueprint are available to describe APIs, OAI aims to bring out a single open specification that covers all use cases. 

Jul  
2017

**OpenAPI Specification 3.0.0** is released, the first release of the specification from the OAI. Version identifier uses semantic versioning. Multiple servers (aliases) are supported but can be overridden by a Path Item Object. Reusable definitions are organized under the Components Object. Parameters can be complex types. Increased reusability, content negotiation, enhanced security, updated parameters, improved examples, links, and callback descriptions are some features this release brings. 

Oct  
2019

At Vancouver, Canada, the first **API Specifications Conference (ASC)** is organized by the OpenAPI Initiative. This conference has its origins in *APIStrat*, an API conference organized for many years by 3Scale. In 2017 and 2018, the OpenAPI Initiative hosted APIStrat that now becomes ASC. ASC welcomes participation from other communities (AsyncAPI, gRPC, GraphQL, OData, etc.). 

Feb  
2021

**OpenAPI Specification 3.1.0** is released. Top-level field `webhooks` is added. An OpenAPI document must have at least one of the top-level fields `paths`, `components` or `webhooks`. The specification is now fully compatible with JSON Schema 2020-12 draft. 

Aug  
2021

Postman publishes an analysis of nearly 200,000 OpenAPI documents downloaded from various sources. Most documents in this study use the older 2.0 specifications. They find that most of them don't include license information. About 21% fail validation. About 2% include a `/status` endpoint while 4% include a `/ready` or `/healthcheck` endpoint. HTTP methods GET (44%), POST (27%) and PUT (15%) are common.