In this tutorial, we are going to learn how to document APIs using Swagger/OpenAPI. Swagger is a powerful yet easy-to-use suite of API developer tools for teams and individuals, enabling development across the entire API lifecycle, from design and documentation, to test and deployment. OpenAPI is a specification for machine-readable interface files for describing, producing, consuming, and visualizing RESTful web services.
After completing this tutorial, you will be capable of:
This tutorial assumes that you have a basic understanding of APIs and RESTful services. Familiarity with JavaScript and Node.js will be beneficial but not required.
Let's start by installing the necessary tools and creating a new project.
npm init
and following the prompts.npm install swagger-ui-express
.app.js
file. This will be the entry point of your application.You will need to create a Swagger JSON file that describes your API. This file follows the OpenAPI specification and includes information about API endpoints, request/response types, and more.
Let's create a Swagger document for a simple API with a single endpoint (/api/greet
) which accepts a GET request and returns a greeting message.
// app.js
const swaggerJsDoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-express");
const swaggerOptions = {
swaggerDefinition: {
info: {
title: "Greeting API",
description: "This is a simple API",
contact: {
name: "Amazing Developer"
},
servers: ["http://localhost:5000"]
}
},
apis: ["app.js"]
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs));
Next, we define our /api/greet
endpoint in the same app.js
file:
/**
* @swagger
* /api/greet:
* get:
* summary: Returns a greeting
* responses:
* 200:
* description: Successful response
*/
app.get('/api/greet', (req, res) => {
res.send('Hello World!');
});
This tutorial covered the basics of documenting APIs using Swagger/OpenAPI. We went through setting up a new project, defining an API using OpenAPI, and generating a documentation page using Swagger UI.
The next steps can be trying to document more complex API with various endpoints, different methods and diverse data structures. You can also look into authorization and authentication in Swagger/OpenAPI.
Some additional resources include the official Swagger documentation and the OpenAPI Specification.
Exercise 1: Create an API with a POST endpoint /api/person
that accepts a name and a job in the request body and returns a message. Document this API using Swagger/OpenAPI.
Exercise 2: Extend the API from exercise 1 by adding error handling. If the request body does not contain a name or a job, the API should return an error. Update the Swagger documentation to include this error case.
/**
* @swagger
* /api/person:
* post:
* summary: Creates a person
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* job:
* type: string
* responses:
* 200:
* description: Successful response
*/
app.post('/api/person', (req, res) => {
const { name, job } = req.body;
res.send(`Hello ${name}, your job is ${job}`);
});
/**
* @swagger
* /api/person:
* post:
* summary: Creates a person
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* job:
* type: string
* responses:
* 200:
* description: Successful response
* 400:
* description: 'Invalid input: name and job are required'
*/
app.post('/api/person', (req, res) => {
const { name, job } = req.body;
if (!name || !job) {
res.status(400).send('Invalid input: name and job are required');
} else {
res.send(`Hello ${name}, your job is ${job}`);
}
});
Remember to practice and explore the different features provided by Swagger/OpenAPI to gain more proficiency. Happy coding!