Quick Recap:What is OpenAPI?OpenAPI Specification (OAS) building blocksBuilding OAS for a TO-DO applicationStep 1:Step 2:Step 3:ConclusionAbout AuthorsSai Manasa IvaturiSrinivas vaddi
Quick Recap:
If you’ve not had a chance to read Part 1 of this tutorial series, click here! or just get a quick recap here.
What is OpenAPI?
OpenAPI is a specification that defines a standard way to describe RESTful APIs using YAML or JSON. It is based on the Swagger specification, which was created by SmartBear Software in 2010. In 2015, Swagger was donated to the Linux Foundation and became part of the OpenAPI Initiative (OAI), which is a consortium of industry leaders that aims to promote and evolve the specification.
OpenAPI was formerly known as Swagger, and it is supported by a large community of developers and organizations such as Google, Microsoft, IBM, and others.
OpenAPI uses either JSON or YAML to define the structure and behavior of an API, such as:
- The base URL and the paths of the API endpoints
- The HTTP methods and the parameters of each endpoint
- The request and the response bodies and headers of each endpoint
- The data models and the schemas of the request and response data
- The security schemes and the authorization requirements of the API
- The metadata and the documentation of the API
OpenAPI offers several benefits for API development, such as:
- It provides a common language and format for describing APIs that can be understood by humans and machines. It uses YAML, a simple and expressive syntax that is easy to read and write. Its YAML people!
- It enables collaboration and communication among developers, testers, clients, and consumers of APIs. It helps to establish a shared and agreed upon understanding of the API design and expectations among all stakeholders.
- It facilitates the design-first approach to API development, where the API specification is created before the implementation. This allows for a test-driven development or parallel development of features that work together.
- It allows for the automatic generation of documentation, code, mock servers, test cases, and other artifacts for APIs using various tools and frameworks.
- It supports the validation and testing of APIs using various tools and frameworks.
To create an OpenAPI document, we need to follow some basic rules and conventions.
The document consists of three main sections:
- info - The info section provides general information about the API, such as title, version, description, contact details, license, etc
- paths - The paths section defines the available endpoints and operations for the API, along with their parameters, responses, security requirements, etc
- components - The components section defines reusable elements that can be referenced in other parts of the document, such as schemas (data models), parameters (common input/output values), responses (common output values), security schemes (authentication methods), etc
For more detailed understanding, it is best to read the OpenAPI specification from here or here.
An OpenAPI document can be written using any text editor or IDE that supports YAML or JSON syntax highlighting. However, a more convenient option is to use https://editor.swagger.io/, which is an online tool that allows creating and editing OpenAPI documents in a graphical user interface. It also enables previewing the documentation, generating code, and testing the API. The above screenshot is an example of a sample API spec for the To-do application that will be discussed further.
OpenAPI Specification (OAS) building blocks
Let's take a closer look at some of the key building blocks of an OAS document and how they can help in designing and documenting an API.
- Schemas: A schema defines the structure and format of a data type, such as an object, array, string, number, boolean, etc. It can also specify validation rules, such as required properties, minimum and maximum values, patterns, etc. Schemas are useful for describing the request and response bodies of the API operations, as well as any other data types in context.
- Parameters: A parameter defines a single piece of information that can be sent or received as part of an API operation. Parameters can be classified into four types: path, query, header, and cookie. Path parameters are used to identify a specific resource within a collection (e.g., /users/{id}). Query parameters are used to filter or sort a collection of resources (e.g., /users?name=John). Header parameters are used to provide additional information about the request or response (e.g., Content-Type). Cookie parameters are used to store session or state information on the client side (e.g., session_id).
- Request Bodies: A request body defines the content of the message body that is sent to the server as part of an API operation. It can be either a schema or a reference to a schema defined in the components section. Request bodies are typically used for creating or updating resources (e.g., POST or PUT requests).
- Responses: A response defines the content of the message body that is returned from the server as part of an API operation. It can be either a schema or a reference to a schema defined in the components section. Responses also include a status code that indicates the outcome of the operation (e.g., 200 OK or 404 Not Found). Responses can also specify headers that provide additional information about the response (e.g., Location).
- Security Schemes: A security scheme defines a mechanism for authenticating and authorizing users to access the API. OAS supports various types of security schemes, such as HTTP basic authentication, HTTP bearer authentication, API keys, OAuth 2.0, OpenID Connect, etc. Security schemes are defined in the components section and can be applied globally or per operation.
Building OAS for a TO-DO application
As we discussed earlier, we will designing the Open API spec for a To-Do application.
We need to have our APIs to do the CRUD operations, that is to create, read, update and delete.
For this let us assume that we have an endpoint that supports HTTP GET, HTTP POST, HTTP PATCH and HTTP DELETE methods for each of the operations mentioned above.
So lets write down our requirements as a table -
ㅤ | READ | CREATE | UPDATE | DELETE |
HTTP METHOD | GET | POST | PATCH | DELETE |
Authorization | n/a | n/a | n/a | n/a |
Headers | Accept: application/json | Content-Type: application/json, Accept: application/json | Content-Type: application/json-patch+json, Accept: application/json | None |
Query Parameters | Optional (filter, sort, limit, offset) | id | id | id |
Request body | None | A To-Do object with title and description properties (id and status are generated by the server) | An array of patch operations to modify the To-Do object (e.g. replace title or status) | None |
Response codes | 200 OK, 401 Unauthorized, 404 Not Found, 500 Internal Server Error | 201 Created, 400 Bad Request, 401 Unauthorized, 500 Internal Server Error | 200 OK, 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error | 204 No Content, 401 Unauthorized, 404 Not Found, 500 Internal Server Error |
Response Body | An array of To-Do objects or an empty array | The created To-Do object with id and status properties | The updated To-Do object | None |
To create an OAS document for the above requirements, we can follow a simple process -
Step 1:
Create a YML file and specify the version of the
openapi
and also add the info
, servers
sections where we can have the metadata about the OAS document.TheTechCruise.com Pyodide Terminal
openapi: 3.0.1
info:
title: OpenAPI definition
version: v0
description: A simple API for managing todo items.
contact:
name: API Support
email: support@example.com
license:
name: Apache 2.0
url: ^1^
servers:
- url: http://backend:7787
description: Generated server url
The above code block shows the basic structure of an OAS document. It has a root-level property named
openapi
that specifies the version of the OAS specification that the document follows (in this case, 3.0.1). It also has a root-level property named info
that provides general information about the API, such as:title
: A short name for the API.
version
: A version number for the API.
description
: A brief summary of what the API does and how it works.
contact
: An object that contains contact information for the API maintainer, such as name and email.
license
: An object that contains license information for the API, such as name and url.
The
info
section can have other optional properties as well, such as termsOfService, externalDocs, etc. Refer to OAS official documentation for more information.The document also has a root-level property named
servers
that lists the base URLs for the API endpoints. Each server object has a url property that specifies the server address, and optionally a description property that provides a human-readable explanation of the server. In this case, there is only one server with a generated url and a description. The server url can have variables that can be replaced by values from another source, such as environment variables or user input. For example, if the server url is http://{username}.example.com/{version}
, then the username and version variables can be substituted by actual values at runtime. The server object can also have a variables property that defines the possible values and defaults for each variable. Refer to OAS official documentation for more information.Step 2:
Create
paths
block and specify the paths. Since we know from the previous section that each path can have a different authorization scheme, headers, request parameters etc, each path
in an OAS document usually encompasses all these things along with extra metadata.Let’s try to understand the OAS spec for the
CREATE
or HTTP POST
operation.TheTechCruise.com Pyodide Terminal
paths:
/api/todos:
post:
tags:
- todo-controller
operationId: createTodo
parameters:
- name: id
in: query
required: false
schema:
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/Todo"
required: true
responses:
'200':
description: OK
content:
'*/*':
schema:
id: string
As we can understand from above,
paths
is a list, where each list item is an object that describes the operations it supports. The above code block shows the definition of the /api/todos
path, which supports only one operation: post
.The
post
object has several properties that provide information about the operation, such as:tags
: A list of tags that group related operations. This can be useful for documentation and tooling purposes.
operationId
: A unique identifier for the operation. This can be used to link to the operation from other parts of the document or external sources.
parameters
: A list of parameters that are applicable for the operation. Each parameter has a name, a location (such asquery
,header
,path
, orcookie
), a flag indicating whether it is required or not, and a schema that defines its data type and format. In this case, the operation accepts an optional query parameter namedid
of type string.
requestBody
: An object that describes the request body that the operation expects. It has a content property that maps media types to schemas. In this case, the operation expects a JSON object that conforms to the schema defined in#/components/schemas/Todo
. The requestBody object also has a required property that indicates whether the body is mandatory or not. In this case, it is true.
responses
: An object that maps HTTP status codes to response objects. Each response object has a description property that provides a brief summary of the response, and a content property that maps media types to schemas. In this case, the operation returns a 200 OK response with any media type and a schema that defines an id property of type string.
Step 3:
Create
components
block and define reusable components that can be referenced by other parts of the document using $ref
. Components can include schemas, parameters, responses, request bodies, headers, security schemes, links, callbacks, examples, and more.Let’s see how we can define a schema component for the Todo object that we used in the previous step.
TheTechCruise.com Pyodide Terminal
Todo:
required:
- completed
- context
- creationDate
- note
- priority
- title
- user
type: object
properties:
assignedTo:
maxItems: 4
minItems: 0
type: array
items:
type: string
attachment:
maxItems: 4
minItems: 0
type: array
items:
type: string
completed:
type: boolean
completionDate:
maxLength: 32
minLength: 0
type: string
context:
maxLength: 255
minLength: 1
type: string
creationDate:
maxLength: 32
minLength: 0
type: string
description:
maxLength: 1000
minLength: 0
type: string
due:
type: string
estimate:
maximum: 9999
minimum: 0
type: integer
format: int32
id:
type: string
images:
maxItems: 4
minItems: 0
type: array
items:
type: string
importance:
type: string
enum:
- LOW
- MEDIUM
- HIGH
inProgress:
type: boolean
note:
maxLength: 200
minLength: 5
type: string
priority:
maximum: 4
minimum: 0
type: integer
format: int32
project:
maxItems: 10
minItems: 0
type: array
items:
type: string
references:
maxItems: 4
minItems: 0
type: array
items:
type: string
related:
maxItems: 4
minItems: 0
type: array
items:
type: string
repeat:
pattern: ^(\*|[0-9]+[hdm])+$
type: string
share:
maxItems: 4
minItems: 0
type: array
items:
type: string
significance:
type: string
enum:
- LOW
- MEDIUM
- HIGH
tags:
maxItems: 10
minItems: 0
type: array
items:
type: string
title:
maxLength: 255
minLength: 1
type: string
urgence:
type: string
enum:
- LOW
- MEDIUM
- HIGH
user:
maxLength: 255
minLength: 1
type: string
The above code block defines a component named
Todo
under the schemas
section of the components
object. The component has a type property that specifies its data type (in this case, object), and a properties property that lists its sub-properties (in this case, title, completed, and dueDate). Each sub-property has a type property that specifies its data type (in this case, string or boolean), and optionally other properties such as description or format. The component also has a required property that lists the sub-properties that are mandatory (in this case, title and completed).By defining components like this, we can avoid duplication and inconsistency in our OAS document. We can reference components using
$ref
with a JSON pointer syntax. For example, to reference the Todo component from another part of the document, we can use $ref: "#/components/schemas/Todo"
.Conclusion
In this article, we have explored the basics of creating an OpenAPI document, which is a standard way to describe the interface and behavior of a web service. We have also learnt about the various parts of the OpenAPI Spec. So now we can build our own!
In the next article, we will learn about the Generators which use the OAS documents to create/generate integrations or codebases for our projects, later on we will see how we can use OpenAPI Generator to generate a JavaScript client that can interact with a web service from a React application.
Don’t miss it!
About Authors
Sai Manasa Ivaturi
I'm a Software Development Engineer based in Atlanta, Georgia with 5+ years of experience in the software industry. My focus area has been Backend development and full-stack development.
View my Resume here.
Masters Degree in Computer Science Indiana University, Bloomington
Jan 22 - May 23
Bachelors Degree in Computer Science Pragati Engineering College, India
Aug 14 - April 18
Certifications and badges
Srinivas vaddi
Hi! I’m a recent master’s graduate from Indiana University Bloomington (IUB) 🎓 and a Software Development Engineer with 4+ years of experience. Looking for #jobs!
My areas of expertise are Software Development, DevOps, Testing, Integration, Data Engineering and Data Analytics. Mostly worked on Python, Django/Flask, Apache Airflow, Apache Spark, AWS, and DevOps. I have a versatile background & a ‘can do’ attitude 🤓.
I like blogging and sharing knowledge. I’ve built a server at home from scratch! I used it to learn various technologies and to contribute to the open-source. I love tech, philosophy, literature, and history. My favorite books 📚 of all time are ‘The Alchemist’ and ‘Chanakya Neeti’ 🙌.
Masters Degree in Computer Science Indiana University, Bloomington Aug 23, 2021 → Dec 17, 2022
Bachelors Degree in Computer Science Gitam University (Deemed to be) Jun 1, 2014 → Apr 1, 2018