RESTful APIs / REST API Testing and Documentation

Documenting APIs with Swagger/OpenAPI

In this tutorial, we'll learn how to document APIs using Swagger/OpenAPI. We'll cover how to describe API endpoints, data structures, and error messages in a standardized format.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers how to test and document REST APIs effectively.

Introduction

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:

  • Defining your APIs using OpenAPI specification
  • Generating a user-friendly documentation page using Swagger UI
  • Describing API endpoints, data structures, and error messages

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.

Step-by-Step Guide

Let's start by installing the necessary tools and creating a new project.

  1. Install Node.js and npm (node package manager) if you have not already done so.
  2. Initialize a new project by running npm init and following the prompts.
  3. Install the Swagger UI Express package by running npm install swagger-ui-express.
  4. Create an app.js file. This will be the entry point of your application.

Defining the API

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!');
});

Summary

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.

Practice Exercises

  1. 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.

  2. 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.

Solutions

  1. Solution 1:
/**
 * @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}`);
});
  1. Solution 2:
/**
 * @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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help