Using Swagger to design and document an API
APIs are essential to all website and software products. Nearly all programmers have dealt with an API and many have had to create their own API. Creating an API is not an easy task. It requires significant planning, development, and maintenance to successfully create an API. In addition, as your API grows it can quickly become very complicated.
Swagger provides three major features for making the API development process easier:
- Swagger Editor
- Swagger UI
- Swagger Codegen
Overview
In this guide I will discuss how Swagger can be used to simplify the API development and documentation process. Swagger is a set of tools created by SMARTBEAR
used to create an API contract
, which is a document written in JSON or YAML that details the API.
An API contract is absolutely vital to the development of an API whether your team is using a design first or a code first approach. The API contract can serve as both a blueprint for the API as well as documentation.
I will walk through an example of how to create an API contract with endpoints, operations, and example responses. In addition, you will discover how Swagger can take your API contract and generate boiler-plate code for your API. This can potentially save significant time and energy depending on your situation.
Table of Contents
YAML
YAML is a language designed for the storage of data which emphasizes human readability. It is very similar to JSON but uses whitespace instead of brackets or curly braces to separate objects. However, JSON has greater performance than YAML.
This makes YAML ideal for an API contract that requires a high level of readability and performance is not too important.
Below is a short example of YAML:
---
name: Billy bob joe
city: Nola #Nola = New Orleans
hobbies:
- Fishing
- Flying
- Lawncare
...
All YAML documents begin with three dashes (---) and ends with three dots (...). This allows multiple YAML documents to be placed in the same .yml
file.
Objects and lists can be created in YAML documents through the use of whitespace. Comments in YAML are created using #
.
I will not spend any more time discussing YAML as Swagger generates the necessary YAML for you. This brief introduction should be sufficient for this guide.
If you are interested in learning more please refer to YAML's documentation.
OpenAPI Specification
The OpenAPI Specification (OAS)
is a very popular standard for developing API contracts. This is the specification that Swagger uses for generating your API contract.
An API contract using OAS 3.0 will contain the following sections:
- Info: Contact info, license info, etc
- Servers: Provides info of server hosting the API
- Security: Provides info on authentication and authorization flows
- Paths: Details API's endpoints
- Tags: Group API endpoints
- ExternalDocs: Additional documentation on the API
- Components: Objects such as schemas or responses that can be reused
In this example you will pretend that you are using a Next.js web application. The API for your application consists of a group of serverless functions hosted on Vercel that are only accessible from your web application. As this API is not available for public consumption and I want to keep this example relatively simple, I will ignore some of the info section and the security section.
Swagger UI
As you add items in the Swagger Editor, you will notice that the right pane of the screen updates with information and interactive features. This feature is called the Swagger UI
.
It allows an easy and intuitive method for interacting with your API contract.
Swagger Editor
This is the feature that you will use to create your API contract. Navigate to Swagger Editor to get started.
A sample project, Swagger Petstore
, should appear. Go ahead and review this example to get an idea of what the API contract looks like. After you have reviewed it, navigate to File
and click Clear Editor
.
I will now focus on the Insert
tab for the remainder of this section.
Info Section
This section details general information for the API. It includes the following fields:
- Title
- Description
- Version
- Terms of Service
- License
- Contact
In this example I will ignore the Terms of Service, License, and Contact fields but for a public, production API you should include these values.
Click Add Info
and your info should appear in the editor. If all of the info (license, paths, external documentation, etc) reappears when you add your info section go ahead and delete it.
Your editor should now look like this:
openapi: 3.0.3
info:
title: SeaTurtleCharter
version: 1.0.11
description: >-
This is a sample SeaTurtleCharter Server based on the OpenAPI 3.0
specification.
Add Path Item
Now click Add Path Item
and add the Path
field and the Summary
field.
You should add a Path Item
for all of your API routes. We will add one more called api/review
.
paths:
/api/rent:
summary: Allows user to rent a sea turtle
/api/review:
summary: Allows user to review past trips
Add Operation
An operation is where you specify what type of request the API endpoint accepts. For the Path select /api/rent
and for Operation select post
as users will be submitting data for reservations.
Add a Summary and a Description. The Operation ID is a unique string used to identify the operation. You will just use the path name for this example. Finally, add a tag for this operation. Tags are used to group similar API operations to increase organization.
You will now add an operation for the api/review
endpoint.
/api/rent:
summary: Allows user to rent a sea turtle
post:
summary: Allows user to rent a sea turtle
description: Allows user to submit a request with data for sea turtle rental
operationId: /api/rent
responses:
default:
description: Default error sample response
tags:
- Rent
/api/review:
summary: Allows user to review past trips
get:
summary: Retrieve past rentals
description: Retrieves information for a user's past rentals
operationId: /api/review
responses:
default:
description: Default error sample response
tags:
- Review
Add Example Response
Now that you have your paths and operations created, you need to add example responses. Select Add Example Response
, the /api/rent
path, and post
operation. For Response
select Add
and enter 200
.
Then select application/json
and add an Example name
and Example Value
. The Example Value can be a simple string, an array, an object, etc. It should reflect exactly what your API will actually return.
NOTE: Include the string User rental added
in the Example Value
input
NOTE: Include the string User rental added
in the Example Value
input
In reality you would most likely want to return the rental confirmation object rather than a simple string. However, a string will work for this example.
After clicking Add Example Response
, you may receive an error should have required property description
. Under the 200
response you just added, add description: User rental added
above content:
. This should remove the error.
Now you will add the remaining example responses to your operations. For each operation in this example you will have a 200 response and a 400 response. In your API you could add more example responses such as 500 or 401.
/api/rent:
summary: Allows user to rent a sea turtle
post:
summary: Allows user to rent a sea turtle
description: Allows user to submit a request with data for sea turtle rental
operationId: /api/rent
responses:
'200':
description: User rental added
content:
application/json:
examples:
Successfully added user rental:
value: User rental added
'400':
description: Failed to add user rental
content:
application/json:
examples:
Failed to add user rental:
value: Failed to add user rental
default:
description: Default error sample response
tags:
- Rent
/api/review:
summary: Allows user to review past trips
get:
summary: Retrieve past rentals
description: Retrieves information for a user's past rentals
operationId: /api/review
responses:
'200':
description: Past user trips retrieved
content:
application/json:
examples:
Past user trips retrieved:
value:
- id: 1,
name: Vacation,
Destination: Bahamas,
Cost: $200
- id: 2,
name: Business,
Destination: Chicago,
Cost: $10
'400':
description: failed to retrieve past trips
content:
application/json:
examples:
Failed to retrieve past trips:
value: Failed to retrieve past trips
default:
description: Default error sample response
tags:
- Review
Request body
You will now add a sample request body to your /api/rent
endpoint. As it is a POST request, it should include information that will be added to the database.
In order to add an example request body, you will need to add a components
section at the bottom of the document. It needs to be all the way at the bottom and should not be indented at all.
components:
schemas:
RentalObject:
type: object
properties:
name:
type: string
email:
type: string
destination:
type: string
xml:
name: RentalObject
On the right-side in the Swagger UI a box labeled Schemas
should now appear with your RentalObject
schema.
Then under the /api/rent
path and post operation you will add the sample request body. It will be placed between operationId
and responses
.
operationId: /api/rent
requestBody:
description: Rental object
content:
application/json:
schema:
$ref: '#/components/schemas/RentalObject'
responses:
Your /api/rent
endpoint should now have a Request body section with an example request body that matches our schema.
Next Steps
This guide was just a brief overview of API development and the Swagger software. As I discussed you could add the following information to your API contract:
- Terms of Service
- Contact Details
- External Documentation
- Security Informtation
- Server Details
In addition, Swagger offers the ability to generate code automatically from your API contract. It can generate server-side code and client-side code for a variety of platforms and languages.
In the Swagger Editor if you click Generate Server
or Generate Client
you can select your language. A file with boilerplate code will download. This boilerplate code is not perfect. You will almost certainly want to modify it. However, it can provide a good starting point.
If you want a more advanced tool for generating code from your API contract check out Swagger Codegen.
If you would like to learn more about developing APIs, these resources are a great place to start: