[Web Dev] OpenAPI
Apr. 19, 2021Let’s say you are a new hire to get started developing and maintaining an application consists of APIs. You are really excited to go ahead and become productive, but you don’t understand the APIs, the services and what it does. Thus you need to dig in line by line to understand what one API do.
The other way you can do is to refer to the OpenAPI and quickly understand what exactly this API does. Great.
What is an OpenAPI
The OpenAPI specification defines how to describe a REST API interface. The description of the REST API, or the OpenAPI definition, is a file, typically in YAML or JSON, that describes what the API/Service can do.
It’s a standardized format for describing your API. It’s both human- and machine-readable. So anyone can look at this definition and understand what the API does, or the OpenAPI definition can be fed into some DevOps automation process, some testing or toolings. With the definition you can describe a few things: the resources including properties and data types, endpoints, operations, parameters, authentication/authorization. It also contains guidance on how to use the REST API.
OpenAPI allows you to extend your REST API with toolings. For example, API validators can take the OpenAPI definition as an input, and run through some validations to ensure that the REST API conforms to certain industry standard; API doc generator for documentation; SDK generators, etc.
Example
This is an example of how an OpenAPI definition may look like:
openapi: "3.0.0"
info:
version: 1.0
description: Manage Company Accounts
servers:
- url: http://mycompany.com/api
paths:
/companies:
get:
operationId: list_companies
responses:
'200':
.
.
.
properties:
id:
type: integer
format: int64
name:
type: string
examples:
{[
{ "id": 0,
"name": "Redily" }
.
.
.
]}
At the top of the file, you have some basic API info, version of OpenAPI, version of the REST API itself, some descriptions. Next, you have a section that describe the API request, we can see the path, the GET HTTP method. The rest of the definition describe the REST API response, for example, the status code, the properties with the data types. Lastly, the definition can have a section for an example response (sample data for you to look at).