Writing an API document is something I hate, and writing an OpenAPI document from scratch is a nightmare.
I checked some auto-api-generation tools and they all need me to modify my codes by adding comments or decorators. I personally don't like it because I wanna keep my code as clean as possible.
Then I was thinking if we could generate an API document based on the unit test because usually the unit test covers all cases of the API, we just need a program to understand the test cases and generate the API document.
So I build Outdoc and here is an example for an express application:
app.js
const express = require('express');
const app = express();
app.get('/projects', (req, res) => {
res.json([{
id: '1',
name: 'project v1'
}, {
id: '2',
name: 'project v2'
}]);
});
app.test.js
const request = require('supertest');
const app = require('./app.js');
describe('api testing', () => {
it('should able to find all', (done) => {
request(app)
.get('/projects')
.set('x-api-key', 'outdoc-test')
.expect(200)
.end(function(err, res) {
if (err) throw err;
done();
});
});
});
For using Outdoc, we simply add a few codes into app.js and run the script.
app.js
const express = require('express');
const app = express();
// New added for using Outdoc
if (process.env.NODE_ENV === "test") {
const { OutDoc } = require('outdoc');
OutDoc.init();
}
package.json
{
"scripts": {
"test": "mocha *.test.js",
"gen-doc": "outdoc npm test"
}
By running npm run gen-doc
, we get an api.yaml as the following
openapi: "3.0.1"
info:
title: "API Document"
version: "1.0.0"
paths:
/projects:
get:
parameters:
- in: "header"
name: "x-api-key"
example: "outdoc-test"
schema:
type: "string"
responses:
200:
description: "OK"
content:
application/json:
schema:
type: "array"
items:
type: "object"
properties:
id:
type: "string"
example: "1"
name:
type: "string"
example: "project v1"
Outdoc can also auto generate tags for multiple endpoints.
Check more options and examples in Github https://github.com/dapi-labs/outdoc
Top comments (0)