Cover Photo by Sigmund on Unsplash
While we are working on number of projects it is really important to document them well. And Swagger is the tool which helps us in doing that. While developing various APIs for different projects you must have experienced the cumbersome process of maintaining the API documentation.
So let's start from basics:
What is REST API?
A REST API (also known as RESTful API) is an application programming interface (API or web API). REST is acronym for REpresentational State Transfer. In layman's terms it is way of allowing two different applications to communicate with each other.
What is OAS?
As per official documentation :
The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.
What is API definition file?
API definition file lists all the functionalities which we can perform using API, also describes the format of the request and response body for each API route
Why create an API definition file?
Helps in creating the design of the API before working on it, this way other stakeholders can review the API structure and can provide the necessary feedback
Interactive API documentation : this helps in actually sending the API calls from document itself
What API definition file contains:
- Server location
- Authorization or security
- All available functionalities in that API
- Request and response body structure of each route in API
Now lets dive into actual creation of the API definition file......
Creating an API definition file:
While creating the API definition and documentation Swagger really helps us. Now you must be thinking
What is Swagger?
It is collection of tools which use open API specification. Below are some of the tools which are listed on their official site.
- Swagger Editor : API editor for designing APIs with the OpenAPI Specification
- Swagger UI : Visualize OpenAPI Specification definitions in an interactive UI
- Swagger codegen : Generate server stubs and client SDKs from OpenAPI Specification definitions
We can create the OAS files in JSON or YAML format. All examples in this article are in YAML format but you can choose the format as per your convenience. Indentation plays very important role in YAML so please keep keen eye on indentation.
Open API specification basic Structure
Below is the basic structure of OAS as explained in official documentation :
openapi: 3.0.0
info:
title: Sample API
description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
version: 0.1.9
servers:
- url: http://api.example.com/v1
description: Optional server description, e.g. Main (production) server
- url: http://staging-api.example.com
description: Optional server description, e.g. Internal staging server for testing
paths:
/users:
get:
summary: Returns a list of users.
description: Optional extended description in CommonMark or HTML.
responses:
'200': # status code
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string
Working of each key present in above documentation is as below:
openapi : REQUIRED. This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses.
info : REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.(title and description is the part of metadata)
- servers : An array of Server Objects, which provide connectivity information to a target server
- paths : REQUIRED. The available paths and operations for the API.
I will try to explain with example, that will help you to understand the OAS functionality more easily:
What does each request will consists of:
- A URL endpoint
- http method
- path parameter/query parameter or both
- request body and responses
Suppose we have an API to get the student details of some xyz college, the details for the API of their particular website are as below:
- A URL endpoint : api.xyz.college
- http method : GET
- path parameter : student id
Then our API request will look like below:
GET https://api.xyz.college/students/{student-id}
Now let's write the OAS definition for this path:
paths:
/students/{student-id}:
get:
summary: get the student information
parameters:
- in: path
name: student-id
description: returns the data about the student with that student id
required: true
schema:
type: integer
responses:
200:
description: Successful response
content :
application/json :
schema: # Response body contents
$ref: '#/components/schemas/Student'
components:
schemas:
Student: # Schema name
type: object
properties:
id:
type: integer
example: 1234 # Property example
name:
type: string
example: Gayatri Kale # Property example
Now you must be wondering what is this $ref key and the path mentioned in front of that key. You will understand the schema once you read below section.
What is schema?
Schema defines the structure of particular object. Schemas can be defined inline or referenced from an external definition via $ref. $ref indicates that particular structure is defined somewhere else in yaml file. Components mentioned above hold various schemas for the specification. For example we can define more schemas for college as done below:
components:
schemas:
Student: # Schema name
type: object
properties:
id:
type: integer
example: 1234 # Property example
name:
type: string
example: Gayatri Kale # Property example
Department: #Schema name
type: object
properties:
faculty number:
type: integer
example: 1234 # Property example
name:
type: string
example: Chemistry # Property example
If you see here we have defined new schema for "Department " in the college, likewise we can create schemas for different objects, this helps in avoiding the duplication of lines and also make the OAS file more organised.
Now let's discuss some of the other important parameters while creating the OAS file
Security
As per official documentation : OpenAPI uses the term security scheme for authentication and authorization schemes. OpenAPI 3.0 lets you describe APIs protected using the following security schemes:
HTTP authentication schemes (they use the Authorization header):
- Basic
- Bearer
- other HTTP schemes as defined by RFC 7235 and HTTP Authentication Scheme Registry
API keys in headers, query string or cookies
- OAuth 2
- OpenID Connect Discovery
Follow the links above for the guides on specific security types.
Below is the example of OAuth 2.0 security scheme, there are several flows present for OAuth 2.0, I am using "Client Credentials" flow here. If you want more information about the different flows then please refer the official swagger documentation .
securitySchemes:
oAuth2ClientCreds:
type: oauth2
description: For more information please visit the official website of the college
flows:
clientCredentials:
tokenUrl: https://api.xyz.com/oauth2/token/
scopes:
write: allows modifying resources
read: allows reading resources
After clicking on Authorize in editor.swagger.io,
you will see below window, where you can enter your client id and client secret key
Below is the complete YAML file for xyz college, copy it and paste into swagger editor to see how it actually works.
openapi: 3.0.3
info:
title: XYZ College API
version: 0.3.0
servers:
- url: https://api.xyz.college
- url: https://api-staging.xyz.college
tags: #Used to group the displayed operations
- name: Student
- name: Department
paths:
/students/{student-id}:
get:
summary: Get the student information
security:
- oAuth2ClientCreds: [read]
tags:
- Student
parameters:
- in: path
name: student-id
description: returns the data about the student with that student id
required: true
schema:
type: integer
responses:
200:
description: Successful response
content :
application/json :
schema: # Response body contents
$ref: '#/components/schemas/Student'
/departments/{department-name}:
get:
summary: Get the department information
security:
- oAuth2ClientCreds: [read]
tags:
- Department
parameters:
- in: path
name: department-name
description: returns the data about the department with that department name
required: true
schema:
type: string
responses:
200:
description: Successful response
content :
application/json :
schema: # Response body contents
$ref: '#/components/schemas/Department'
components:
schemas:
Student: # Schema name
type: object
properties:
id:
type: integer
example: 1234 # Property example
name:
type: string
example: Gayatri Kale # Property example
Department: #Schema name
type: object
properties:
faculty number:
type: integer
example: 1234 # Property example
name:
type: string
example: Chemistry # Property example
securitySchemes:
oAuth2ClientCreds:
type: oauth2
description: For more information please visit the official website of the college
flows:
clientCredentials:
tokenUrl: https://api.xyz.com/oauth2/token/
scopes:
write: allows modifying resources
read: allows reading resources
Above file look like below in Swagger Editor :
What we learned in this article:
- What is REST API
- What is OAS
- What is API definition file
- What API definition file contains
- How to create API definition file using Swagger
- Important parameters while creating the OAS file
I hope all these points will help you to start your journey with interactive API documentation. If you find this article useful then do share it with your friends, family and colleagues and make their life little bit easier while maintaining the API documentation ๐