The target
- The KOA project API interface automatically generates API documentation
- Simple and does not require much configuration
The end of the
There are two main libraries
- Render JSON file API data as Swagger UI with koA2-Swagger UI.
npm i koa2-swagger-ui -D
Copy the code
app.js
const Koa = require('koa')
const swagger = require('koa2-swagger-ui')
const koa = new Koa()
app.use(
koaSwagger({
routePrefix: '/swagger'.// host at /swagger instead of default /docs
swaggerOptions: {
url: 'http://petstore.swagger.io/v2/swagger.json'.// example path to json}})); app.listen(3000)
Copy the code
- Another library
The KOA2-Swagger-UI library needs to provide AN API JSON file. The Swagger-Jsdoc library can generate such JSON files from annotations. It’s over before it even started. It’s that simple.
Install the swagger – jsdoc
npm i swagger-jsdoc -D
Copy the code
swagger.conf.js
const swaggerJSDoc = require('swagger-jsdoc')
const swaggerDefinition = {
info: {
// API informations (required)
title: 'Hello World'.// Title (required)
version: '1.0.0'.// Version (required)
description: 'A sample API'.// Description (optional)
},
host: `localhost:3000`.// Host (optional)
basePath: '/'.// Base path (optional)
};
const options = {
swaggerDefinition,
apis: ['./routes/*.js'].// all api
};
const swaggerSpec = swaggerJSDoc(options); // swaggerSpec is the generated API JSON
Copy the code
Note that Swagger-docs generates JSON from comments in files under apis. So we need to write comments like this:
routes/user.js
/** * @swagger * * /user/: * get: * description: get all users * produces: * - application/json * responses: * 200: * description: get all users */
Copy the code
Can also have parameters, detailed writing method to see the official website examples. Swagger annotation
/* parameters: * - name: username * description: Username to use for login. * in: formData * required: true * type: string * - name: password * description: User's password. * in: formData * required: true * type: string */
Copy the code
To avoid maintaining this file separately, create a new route
app.js
route.get('/apijson'.async (ctx) => {
ctx.body = swaggerSpec
})
Copy the code
The corresponding koa2 swagger – UI swaggerOptions. Url to http://localhost:3000/apijson
Direct access to the http://localhost:3000/swagger can see the interface
portal
Each module is simply broken down, the complete code on Github
- ERPServer