In team development, a good API document can reduce a lot of communication costs , and can also enable a newcomer to quickly get started with the business.
foreword
- swagger ui is a powerful tool for API online document generation and testing, and it is currently found to be the best.
- Why is it easy to use? Demo Portal
- Support API to automatically generate synchronized online documents
- These documents can be used for project internal API audit
- Make it easy for testers to understand the API
- These documents can be published as part of the customer product documentation
- Support API specification code generation, the generated client and server skeleton code can speed up development and testing
- Support API to automatically generate synchronized online documents
In a word, it is easy to use and powerful. Below I will summarize how to quickly build an API documentation tool based on Node and Swagger UI locally
Environment build
- Download Swagger UI (you can also download the zip file directly)
git clone https://github.com/swagger-api/swagger-ui.git
- install express
- Create an empty folder node_app
mkdir node_app
- Initialize node, create package.json file()
➜ ~ ✗ >cd node_ap
➜ ~/node_app ✗ >npm init
// 下面的看你心情填写
name: (node_app) node_app
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
- install express
➜ ~/node_app git:(master) ✗ >npm install express --save
- Create index.js
➜ ~/node_app git:(master) ✗ >vim index.js
- Paste the following code as index.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
- Create an empty directory public in node_app
➜ ~/node_app git:(master) ✗ >mkdir public
➜ ~/node_app git:(master) ✗ >cd public
- modify route
➜ ~/node_app/public git:(master) ✗ >vim ../index.js
//在文件第三行插入下面这句话
app.use('/static', express.static('public'));
-
Copy all the files in the dist directory in the downloaded Swagger UI file to the public folder.
Directory Structure - open node
➜ ~/node_app git:(master) ✗ >node index.js
- Open the browser and enter http://localhost:3000/static/index.html
So far, you have configured the official demo locally. Of course, you can also build this on the server.
Write documentation and publish
- Write API documentation using Swagger Editor
- The syntax on the Swagger Editor is based on yaml, but don’t be afraid, just watch the official demo for 10 minutes.
-
export test.json
export method - Put test.json in the node_app/public directory.
- Use the editor to modify
url = "http://petstore.swagger.io/v2/swagger.json";
tourl = "/static/test.json";
http://localhost:3000/static/index.html
Restart the node service, open the api document you wrote yourself in the browser