Swagger is a powerful tool for documenting and testing APIs. With Swagger, you can create a comprehensive and user-friendly documentation for your API, as well as test your API endpoints directly from the documentation.
In this blog post, we will walk through the steps to create a basic Swagger documentation for a Node.js API using the swagger-ui-express and yamljs libraries.
Step 1: Install the Required Packages
The first step is to install the required packages. In your project directory, open your terminal and run the following command:
code
npm i nodemon swagger-ui-express express yamljs
This will install nodemon, swagger-ui-express, express, and yamljs.
Step 2: Create an Index.js File
Next, create an index.js file in your project directory and add the following code:
javascript code
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./api.yaml');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(8083, () => console.log('Server started on port 8083'));
This code does the following:
Imports the necessary modules (express, swagger-ui-express, and yamljs).
Loads the Swagger document from the api.yaml file.
Creates a new express app.
Mounts the Swagger UI middleware at /api-docs.
Starts the server on port 8083.
Step 3: Create the Swagger YAML File
Next, create a file named api.yaml in your project directory and add the following code:
yaml code
openapi: 3.0.3
info:
title: My API
description: A simple API to test Swagger documentation.
version: 1.0.0
servers:
- url: http://localhost:8083
paths:
/hello:
get:
summary: Returns a hello message.
responses:
'200':
description: A successful response.
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: Hello, World!
This code defines the Swagger specification for our API, including the API title, description, and version, as well as the API endpoints and their responses.
In this example, we define a single endpoint at /hello that returns a JSON object with a message property set to "Hello, World!".
Step 4: Start the Server
Finally, start the server by running the following command in your terminal:
Copy code
nodemon index.js
This will start the server on port 8083.
Step 5: View the Swagger Documentation
To view the Swagger documentation, open your web browser and navigate to http://localhost:8083/api-docs. You should see the Swagger UI, which displays the API endpoints and their documentation.
Click on the /hello endpoint to expand it, and then click the "Try it out" button. This will allow you to test the endpoint by sending a request and receiving a response directly from the documentation.
Congratulations! You have now created a basic Swagger documentation for your Node.js API. From here, you can continue to customize and expand the documentation to suit your needs.
No comments:
Post a Comment