Level 58
To create a simple API with Swagger, you can follow these steps:
- Install the Swagger UI package using npm:
npm install swagger-ui
- Create a Swagger specification file in YAML or JSON format. This file should describe your API endpoints, parameters, responses, and other details. Here's an example:
swagger: '2.0'
info:
title: My API
version: '1.0'
paths:
/users:
get:
summary: Get a list of users
responses:
'200':
description: OK
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
- Serve the Swagger UI package and your specification file using a web server. You can use a simple Node.js server for this:
const express = require('express');
const swaggerUi = require('swagger-ui');
const swaggerDocument = require('./swagger.yaml');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => {
console.log('Swagger UI is running on http://localhost:3000/api-docs');
});
- Open your web browser and navigate to http://localhost:3000/api-docs to see the Swagger UI interface. You should be able to browse your API endpoints, test them, and see the responses.
Note that this is just a basic example, and you can customize your Swagger specification and UI to fit your needs. You can also use tools like Swagger Editor or SwaggerHub to create and manage your API documentation.