30

According to Swagger website, there are two approaches: Bottom-up and Top-down.

I have an existing NodeJS server that I'd like to deploy in the Azure enviroment, that require a swagger document (API APP).

Does anyone know a tool for generating the swagger using the code? Even better if you could point a tutorial. I couldn't find it.

Ernani
  • 1,009
  • 3
  • 15
  • 26
  • 3
    Which framework dose your Nodejs server built on? If is Express, you can refer to https://github.com/shawngong/Swagger-Node-Express-For-Existing-APIs. To deploy Nodejs app to Azure Web Apps, please refer to https://azure.microsoft.com/en-us/documentation/articles/web-sites-nodejs-develop-deploy-mac/ – Gary Liu Nov 05 '15 at 05:49
  • @GaryLiu-MSFT yes I used express. I tried this project you sent, but I couldn't really understand it. In the tutorial it tells you to prepare everything, and by the way, a lot of code, and then it doesn't say what to do to generate the swagger doc.... – Ernani Nov 05 '15 at 12:29
  • I think you can first follow the step-by-step tutorial to build the swagger doc first, or could you tell me which step blocks you up? – Gary Liu Nov 06 '15 at 01:22
  • 1
    Maybe you need something like this? http://mherman.org/blog/2016/05/26/swagger-and-nodejs/#.WZ7LQCgjHIU According to this, you can use module 'swagger-jsdoc' to generate swagger doc from your project. – Margarita Krivorot Aug 24 '17 at 13:53

5 Answers5

20

Question is a bit old but still. It is possible to generate completely automatically Swagger (OpenAPI) specification just by embedding analysis middleware like this: https://github.com/mpashkovskiy/express-oas-generator

const express = require('express');    
const expressOasGenerator = require('express-oas-generator');
let app = express();
expressOasGenerator.init(app, {});

run some client or REST API tests agains your service and open http://host:port/api-docs

mpashkovskiy
  • 288
  • 3
  • 3
  • 1
    Hi thanks for the info i am also using express-oas-generator to make api documentation its working but in response it will not update in ui some times it update some time its not can you help to fix that issues – s.chandran sha Jul 12 '19 at 07:45
  • sure, may I ask you to create an issue and describe the problem in details here: https://github.com/mpashkovskiy/express-oas-generator/issues ? – mpashkovskiy Jul 13 '19 at 13:22
  • Hi, so you're the creator of `express-oas-generator`. I love it and use it in my Express app. One thing I miss is the ability to populate body, headers, query, etc. dynamically like Fastify. Like you add a middleware function, passing a schema as its parameter, and it gets passed to OAS Gen. Any plans for adding this functionality in a future version? – Mr. X Jul 28 '22 at 17:55
12

It’s not difficult to integrate Swagger in exist express applications following this tutorial.

Generally, we can follow these steps:

  1. Add the dependencies in our package.json, and run npm install to install them. The dependencies should be:

    "dependencies": {
            "swagger-node-express": "~2.0",
            "minimist": "*",
            "body-parser": "1.9.x",
            ...
    }
    
  2. Download the zip project of Swagger-UI, copy the dist folder into the root directory of our project, the directory should almost like:

enter image description here

  1. Introduce the dependencies at the beginnng of app.js:

    var argv = require('minimist')(process.argv.slice(2));
    var swagger = require("swagger-node-express");
    var bodyParser = require( 'body-parser' );
    
  2. Set up a subpath for swagger doc:

    var subpath = express();
    app.use(bodyParser());
    app.use("/v1", subpath);
    swagger.setAppHandler(subpath);
    
  3. Make sure that /dist is able to serve static files in express: app.use(express.static('dist'));

  4. Set the info for API:

    swagger.setApiInfo({
        title: "example API",
        description: "API to do something, manage something...",
        termsOfServiceUrl: "",
        contact: "yourname@something.com",
        license: "",
        licenseUrl: ""
    });
    
  5. Introduce /dist/index.html for swagger UI:

    subpath.get('/', function (req, res) {
        res.sendfile(__dirname + '/dist/index.html');
    });
    
  6. Complete the swagger configurations:

    swagger.configureSwaggerPaths('', 'api-docs', '');
    
    var domain = 'localhost';
    if(argv.domain !== undefined)
        domain = argv.domain;
    else
        console.log('No --domain=xxx specified, taking default hostname "localhost".');
    var applicationUrl = 'http://' + domain;
    swagger.configure(applicationUrl, '1.0.0');
    
  7. Configure doc file dependence in /dist/index.html:

    if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
    } else {
        <del>url = "http://petstore.swagger.io/v2/swagger.json";</del>
        url = "/api-docs.json";
    }
    
  8. Create api-docs.json file with the info of your APIs, put it in the dist folder.

Run the Express app on local, visit http://localhost:3000/v1, we can check the swagger doc.

Here is my test sample repo for your reference.

M-A. Fernandes
  • 530
  • 5
  • 13
Gary Liu
  • 13,758
  • 1
  • 17
  • 32
  • 63
    This doesn't "generate" anything. It simply serves swaggerUI alongside an app? – Tony Gutierrez Jun 27 '16 at 14:35
  • I generated simple swagger.json from my express 3 apps to import to Postman app via https://www.npmjs.com/package/express-swagger-export package. I built it for myself, but maybe it useful for someone. – Vlad Tsepelev Nov 27 '16 at 10:06
  • Will Swagger Editor will work with this after `swagger project editor`? –  Jul 10 '17 at 06:46
  • 4
    Downvote, because it is not generating, it is manual work, and not "not difficult". – Елин Й. Aug 23 '19 at 14:28
2

To my knowledge, your options are:

  1. Using swagger-node-express which is very cumbersome in my opinion.
  2. Writing up the swagger document manually yourself with the help of swagger editor as suggested in this SO Answer

If you go for option 2, you could use swagger-ui-express to generate the swagger-ui

Ahmad Abdelghany
  • 11,983
  • 5
  • 41
  • 36
2

A lot of developers are still having this problem so I built an open-source tool to help -- the tool is kind of like Git for APIs. It works by running a proxy while you're developing the API, analyzing the traffic, and updating the spec for you as the API's behavior changes. Hopefully, the workflow saves you a lot of time: https://github.com/opticdev/optic

centree
  • 2,399
  • 7
  • 28
  • 32
2

Most alternatives require some sort of API specification through Json, Yaml or even embedded in JSdocs. On the other hand there are some runtime analyzers intercepting HTTP requests and building that specification on-demand.

express-sitemap-html follows a different approach inspecting the express object and its routes at setup time. Thus it always provides an up-to-date swagger UI for installed routes on existing express instance.

const sitemap = require('express-sitemap-html')
...
sitemap.swagger('Title', app) // app is an express instance

Then get swagger UI from your domain /api-docs.

Miguel Gamboa
  • 8,855
  • 7
  • 47
  • 94
  • could you help to clarify, please, why after generation routes looks like `/apiauth` and `/apiuser` instead of `/api/auth` and `/api/user`? – Mike Datsko Nov 15 '22 at 23:45
  • Hi @MikeDatsko I am not getting your doubt. You may check the example provided in https://github.com/fmcarvalho/express-sitemap-html repository. Run it with `node example\app.js` and you may check the sitemap in `http://localhost:3000/sitemap` or `http://localhost:3000/api-docs/#/`. – Miguel Gamboa Nov 16 '22 at 10:31
  • yes, I did like in example, and this is what I see there https://www.dropbox.com/s/9erszn17rf4v446/Screenshot.png?dl=0 – Mike Datsko Nov 16 '22 at 22:18
  • Which line number did you find a route with path auth or user? https://github.com/fmcarvalho/express-sitemap-html/blob/master/example/app.js – Miguel Gamboa Nov 17 '22 at 12:32
  • the difference with your example is that I used `app.use`. can it be the root cause of the issue? – Mike Datsko Nov 18 '22 at 21:13