Giter Site home page Giter Site logo

scottie1984 / swagger-ui-express Goto Github PK

View Code? Open in Web Editor NEW
1.4K 15.0 225.0 10.67 MB

Adds middleware to your express app to serve the Swagger UI bound to your Swagger document. This acts as living documentation for your API hosted from within your app.

License: MIT License

JavaScript 38.96% CSS 7.02% HTML 54.02%

swagger-ui-express's Introduction

Swagger UI Express

Statements Branches Functions Lines
Statements Branches Functions Lines

This module allows you to serve auto-generated swagger-ui generated API docs from express, based on a swagger.json file. The result is living documentation for your API hosted from your API server via a route.

Swagger version is pulled from npm module swagger-ui-dist. Please use a lock file or specify the version of swagger-ui-dist you want to ensure it is consistent across environments.

You may be also interested in:

  • swagger-jsdoc: Allows you to markup routes with jsdoc comments. It then produces a full swagger yml config dynamically, which you can pass to this module to produce documentation. See below under the usage section for more info.
  • swagger tools: Various tools, including swagger editor, swagger code gen etc.

Usage

Install using npm:

$ npm install swagger-ui-express

Express setup app.js

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

or if you are using Express router

const router = require('express').Router();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

router.use('/api-docs', swaggerUi.serve);
router.get('/api-docs', swaggerUi.setup(swaggerDocument));

Open http://<app_host>:<app_port>/api-docs in your browser to view the documentation.

If you want to set up routing based on the swagger document checkout swagger-express-router

If you are using swagger-jsdoc simply pass the swaggerSpec into the setup function:

// Initialize swagger-jsdoc -> returns validated swagger spec in json format
const swaggerSpec = swaggerJSDoc(options);

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

Swagger Explorer

By default the Swagger Explorer bar is hidden, to display it pass true as the 'explorer' property of the options to the setup function:

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  explorer: true
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

Custom swagger options

To pass custom options e.g. validatorUrl, to the SwaggerUi client pass an object as the 'swaggerOptions' property of the options to the setup function:

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  swaggerOptions: {
    validatorUrl: null
  }
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

For all the available options, refer to Swagger UI Configuration

Custom CSS styles

To customize the style of the swagger page, you can pass custom CSS as the 'customCss' property of the options to the setup function.

E.g. to hide the swagger header:

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customCss: '.swagger-ui .topbar { display: none }'
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

Custom CSS styles from Url

You can also pass the url to a custom css file, the value must be the public url of the file and can be relative or absolute to the swagger path.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customCssUrl: '/custom.css'
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

You can also pass an array of css urls to load multiple css files.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customCssUrl: [
    '/custom.css',
    'https://example.com/other-custom.css'
  ]
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

Custom JS

If you would like to have full control over your HTML you can provide your own javascript file, value accepts absolute or relative path. Value must be the public url of the js file.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customJs: '/custom.js'
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

You can also pass an array of js urls to load multiple js files.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customJs: [
    '/custom.js',
    'https://example.com/other-custom.js'
  ]
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

It is also possible to add inline javascript, either as string or array of string.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customJsStr: 'console.log("Hello World")'
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
  customJsStr: [
    'console.log("Hello World")',
    `
    var x = 1
    console.log(x)
    `
  ]
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

Load swagger from url

To load your swagger from a url instead of injecting the document, pass null as the first parameter, and pass the relative or absolute URL as the 'url' property to 'swaggerOptions' in the setup function.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');

var options = {
  swaggerOptions: {
    url: 'http://petstore.swagger.io/v2/swagger.json'
  }
}

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));

To load multiple swagger documents from urls as a dropdown in the explorer bar, pass an array of object with name and url to 'urls' property to 'swaggerOptions' in the setup function.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');

var options = {
  explorer: true,
  swaggerOptions: {
    urls: [
      {
        url: 'http://petstore.swagger.io/v2/swagger.json',
        name: 'Spec1'
      },
      {
        url: 'http://petstore.swagger.io/v2/swagger.json',
        name: 'Spec2'
      }
    ]
  }
}

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));

Make sure 'explorer' option is set to 'true' in your setup options for the dropdown to be visible.

Load swagger from yaml file

To load your swagger specification yaml file you need to use a module able to convert yaml to json; for instance yaml.

npm install yaml
const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const fs = require("fs")
const YAML = require('yaml')

const file  = fs.readFileSync('./swagger.yaml', 'utf8')
const swaggerDocument = YAML.parse(file)

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Modify swagger file on the fly before load

To dynamically set the host, or any other content, in the swagger file based on the incoming request object you may pass the json via the req object; to achieve this just do not pass the the swagger json to the setup function and it will look for swaggerDoc in the req object.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {}

app.use('/api-docs', function(req, res, next){
    swaggerDocument.host = req.get('host');
    req.swaggerDoc = swaggerDocument;
    next();
}, swaggerUi.serveFiles(swaggerDocument, options), swaggerUi.setup());

Two swagger documents

To run 2 swagger ui instances with different swagger documents, use the serveFiles function instead of the serve function. The serveFiles function has the same signature as the setup function.

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocumentOne = require('./swagger-one.json');
const swaggerDocumentTwo = require('./swagger-two.json');

var options = {}

app.use('/api-docs-one', swaggerUi.serveFiles(swaggerDocumentOne, options), swaggerUi.setup(swaggerDocumentOne));

app.use('/api-docs-two', swaggerUi.serveFiles(swaggerDocumentTwo, options), swaggerUi.setup(swaggerDocumentTwo));

app.use('/api-docs-dynamic', function(req, res, next){
  req.swaggerDoc = swaggerDocument;
  next();
}, swaggerUi.serveFiles(), swaggerUi.setup());

Link to Swagger document

To render a link to the swagger document for downloading within the swagger ui - then serve the swagger doc as an endpoint and use the url option to point to it:

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

var options = {
    swaggerOptions: {
        url: "/api-docs/swagger.json",
    },
}
app.get("/api-docs/swagger.json", (req, res) => res.json(swaggerDocument));
app.use('/api-docs', swaggerUi.serveFiles(null, options), swaggerUi.setup(null, options));

Requirements

  • Node v0.10.32 or above
  • Express 4 or above

Testing

  • Install phantom
  • npm install
  • npm test

swagger-ui-express's People

Contributors

alexmassy avatar amirsasson avatar antonve avatar artyhedgehog avatar blackcathacker avatar camipozas avatar caryyu avatar chgeo avatar dukvanduken avatar edalbrelord avatar ffflorian avatar h3nste1n avatar juninhofreitas avatar kahunacohen avatar kroonprins avatar litichevskiydv avatar lukas-reining avatar marcobiedermann avatar muraliprajapati avatar nazar avatar nitrocode avatar rdeluxe avatar scottie1984 avatar shockey avatar stefanreininger avatar thomasleveil avatar tingstad avatar vabhishek-me avatar varanauskas avatar wjthieme avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swagger-ui-express's Issues

jwt authentication?

Is jwt authentication supported in this package?
If so how do i implement it?

I've tried:

"securityDefinitions": {
        "jwt": {
            "type": "apiKey",
            "in": "header",
            "name": "Authorization"
        }
    },
    "security": [
        {
            "jwt": []
        }
    ]

I've been looking all over the place for a guide or something similar but nothing is coming up.

Thanks

Swagger UI with CSP blocking 'unsafe-inline'

I am attempting to use Swagger-UI-Express within an SPA that uses CSP and blocks 'unsafe-inline' to protect against potential XSS vulnerabilities. This breaks the swagger UI due the inline <script> tag. My proposed solution for this is to move this js into a static file. Maybe 'swagger-ui-init.js'. Moving all template options into a separate hidden div that contains a stringified json object with all pertinent options. The swagger-ui-init would then load these options via document.getElementById.innerText and JSON.parse.

Thoughts or concerns? Happy to submit a PR if this all seems reasonable.

How to set the client_id for OAuth 2

I'm trying to integrate with AuthO so basically, I need to configure swagger to use OAuth 2.0

My problem right now is I can't find a way to override
clientId: "your-client-id"
from IndexTemplate on line 60

Any tips?

Cannot load YAML file (Version 3.0.0)

I attempted to load YAML to use as following code below:

const swaggerUI = require('swagger-ui-express')
const YAML = require('yamljs')
const path = require('path')
const swaggerDocument = YAML.load(path.join(__dirname, '/swagger.yaml'))
app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDocument))

When I tried to npm start it displayed the error like this:

fs.js:667 return binding.open(pathModule.toNamespacedPath(path),

Error: ENOENT: no such file or directory, open '<directory>/node_modules/swagger-ui-express/swagger-ui-init.js'

However, I reverted back to version 2.0.15 and it worked.

formData send String instead Array

I have the next configuration of data, and it is rendered properly as array input in UI (with different fields for each value).

  • name: test
         in: formData
         type: array
           items:
           type: integer

But when I trying to send this data, it causes next curl string:
curl -X POST "http: // localhost: 3000 / test" -H "accept: application / json" -H "Content-Type: application / x-www-form-urlencoded" -d "test = 1,2,3,4 "
and node receiving this data as string type.
I think when I POST'ing formData with an array type, it should looks like the request below, which leads to the correct sending of the array data type:
curl -X POST "http: // localhost: 3000 / test" -H "accept: application / json" -H "Content-Type: application / x-www-form-urlencoded" -d 'test=1&test=2&test=3&test=4'

How can I achieve this?

Does the new release support OAS 3?

I see that the library has been updated to Swagger 3.4.4, but for some reason I cannot configure my JSON config except with OAS 2 format.

Am I missing something?

Thanks!

securityDefinitions not supported

I noticed securityDefinitions are not supported or at least the authorize button does not appear like it does in Petstore with a valid security definition:

securityDefinitions: {
   api_key: {
      type: "apiKey",
      name: "api_key",
      in: "header"
   }
}

This is most likely due to an old version of Sawgger UI. How about loading the dependencies from a CDN ( https://cdnjs.com/libraries/swagger-ui ) or NPM?

Input value not passed on url when testing end point.

I am using the following:
"swagger-express-jsdoc": "^1.0.3",
"swagger-jsdoc": "^1.9.7",
"swagger-ui-express": "^2.0.15"

path: /chemicals/:id
action: get
I have an end point that takes an integer as an input parameter.

  • parameters:
    
  •   - name: id
    
  •     in: path
    
  •     description: id for a specific chemical
    
  •     required: true
    
  •     schema:
    
  •       type: integer
    

I am able to type a number in the ui and hit execute but the parameter value is always ':id' instead of the value I passed in. The end point works fine testing it from Insomnia.

endpoints collapsed by default?

Anyone got the endpoints collapsed by default?
This does't seems to be the options, but doesn't to do the trick:

swaggerUi.setup(swaggerDocument, false, {docExpansion:"none"})

Update swagger-ui dependencie to 3.0.19

Hi!

The tagsSorter option just came back in swagger-ui 3.0.19 (it was previously apisSorter and was not working). It would be awesome to have access to it as quickly as possible.

Thank you.

what is the customization story

what is the preferred way to use the latest version of swagger-ui (ex: 2.2.8 at the time of this writing instead of 2.1.5 built in swagger-ui-express)?
How do I provide my own UI customisations?

Thank you.

Pass options to SwaggerUi

I am running my instance of swagger on an internal network. Swagger UI goes out to http://online.swagger.io/ to validate my specification. Seeing online.swagger.io can't reach my instance I get an error at the bottom of the page. This issue can be seen here http://stackoverflow.com/questions/27808804/swagger-ui-shows-error-validation-when-deployed

I need to pass "validatorUrl : null" as a parameter into SwaggerUI so it doesn't try to validate my specification against online.swagger.io

x-csrf-token: Required

Hi @scottie1984

For all the queries other than GET, we get the error message x-csrf-token: Required .

Currently the only workaround I found was updating the swagger specification with additional header to all POST, PUT, DELETE as x-csrf-token and manually fetch the token and pass it.

Is there a better way of solving this issue? I could find there are a lot of topics / bugs around this in Internet but I couldn't find the right solution. Could you please help me?

Best Regards,
Kishore Kumar

Router

When I setup this package on the root route, all my api endpoints fail to work.


app.use('/', swaggerUi.serve, swaggerUi.setup(swaggerDoc, false, options, '.swagger-ui .topbar { background-color: rgb(112, 111, 111); }'));

How can I fix this?

When swagger-ui-express will support Open API 3.0 (swagger-ui v3.13.0)

Hi,

I love Swagger and I tried the new Open API 3.0 but currently it only supported by the swagger-ui 3.13.0 and I would like to know when swagger-ui-express will be updated for this version.

FYI I tested it with my swagger.yaml file (OAS 3.0) that I have converted with yamljs as it says in the documentation and everything seems to work but I got an error from swagger-ui-bundle.js:62:130704 (o is undefined) when I try to execute a route.
I suppose it's due to my swagger.yaml version.

So if you have some informations about a new release, it would be great!

Thank you in advance!

File Upload input for parameter type file

Hi,

I was just wondering how I add a file input for parameter that has parameterType="formData" and type="file".

If I use SwaggerUI.serve from swagger-ui-express, there's no input field for type="file":
Swagger-ui-express

If I switch to SwaggerUI from SwaggerUI's repo (like there assets file), they do have input field for file:
SwaggerUI Repo

Thank you.

EDIT: My hands are fast. Forgot to hit TRY IT OUT.

Disable (or fix) Try it out buttons

There are a couple reasons why "Try it out" doesn't work with my instantiation of swagger-ui-express.

  • My API routes lives in a sub-directory (i.e. https://mydomain.com/api/), and I can't figure out how to make the Try it out button include /api path in the calls it composes.
  • My API uses JWT for authentication and, afaik, there is no way for a user to drop in a token to use and have that be included in an HTTP header "Authorization: Bearer jwt-token-here".

Am I mistaken about either of the above? If not, is there a way for me to omit the Try it out buttons?

Redirect loop when serving static

Using version 3.0.1

Library creates a middleware for serving static with redirect option set to true (default is true)

var serve = express.static(__dirname + '/static');  // Means express.static(__dirname + '/static', { redirect: true }); 

This causes infinite redirect when I try to load .../api-docs endpoint. Constantly redirecting to api-docs endpoint and throws too many redirects error

I solved it with a workaround replacing the 'serve' with my own implementation disabling the redirect on static middleware

const staticPathForSwagger = () => {
    // tslint:disable-next-line:no-eval
    const dir = eval('require.resolve("swagger-ui-express")');
    return express.static(Path.dirname(dir) + '/static', { redirect: false });
};
this.express.use('/api-docs/', staticPathForSwagger(), swaggerUI.setup(swaggerDocument));

What could be the reason of it ? Can't figure it out
Using webpack 4.1.1 with serverless-webpack 5.0. Can this be a post-transpile issue? I have basic knowledge about transpilers.

Serving swagger-ui-express from route subdir

My node/express application has the following directory structure:

/app.js
/routes.1/apidoc.js

where apidocs.js basically contains:

const router = require('express').Router(),
  swaggerUi = require('swagger-ui-express'),
  YAML = require('yamljs'),
  path = require("path"),
  swaggerDocument = YAML.load(path.join(__dirname + '/../api.1/swagger2.yaml'));

router.get('/', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

When I access localhost/1/apidocs I get an "almost good" response, which means the swagger-ui index.html is loaded, but its references to all CSS and JS files are wrong, therefore failing to load the page.

I can see the index.html file uses a relative path

<script src="./swagger-ui-express/static/swagger-ui-bundle.js"> </script>

which is apparently points to an invalid path when calling the route via the browser, for example

Request URL:http://localhost:30300/1/apidoc/swagger-ui.css
Request Method:GET
Status Code:404 Not Found

So what I see from this reponse, the base URL is of my route and that's why swagger-ui.css cannot be found, since is located under the node_modules/etc/etc.

So my questions are

Does swagger-ui-express support what I am trying to do here?

If it does, what am I doing wrong?

Thanks

Paulo

Dynamic Base URL and Scheme

We are hosting our API on multiple stages. Due to this, the base URL and Scheme are changing. As the Swagger file (version 2) has only one static value for Base URL, we needed to adapt it manually so far.

I am not sure whether handling different stages is in the scope of Swagger UI, however support for it would be great.

In the meantime, we have come up with the following workaround, in order to improve the situation:

router.use(
  swaggerUi.serve,
  function(req, res) {
    swaggerDocument.host = req.get('host'); // Replace hardcoded host information in Swagger file
    swaggerDocument.schemes = [req.protocol]; // Replace hardcoded protocol information in Swagger file
    swaggerUi.setup(swaggerDocument)(req, res);
  }
);

Is there a way to keep original favicon?

Thanks for this great library!

Currently when I load the swagger route in my app, the favicon changes to the green-ish Swagger favicon. Is there an option to keep my app's original favicon?

data post not sent

Hello,

I'm trying ti use the swagger-ui-express for my application.
All work fine, but when i try to use "post" data in the swagger-ui, they aren't send to my application.

Extract of my swagger.json
"parameters": [
{
"name": "match",
"in": "query",
"description": "pattern de recherche dans l annuaire",
"required": false,
"type": "string"
},
{
"name": "p",
"in": "query",
"description": "Numéro de la page.",
"required": false,
"type": "integer",
"format": "int32"
},
{
"in": "body",
"name": "authentification",
"required": true,
"description": "login/mdp LDAP",
"schema": {
"$ref": "#/definitions/authentification"
}
}
]

The "Curl" generated code works, but in the web swagger ui part, i have a 400 error code.
If i check the network, we can see that the "post" data aren't send to my server.

Do you know why ?

If i test without authentication (delete all post data needed), all work fine too.

configure swagger-ui to root - "/"

I am trying to serve the swagger-ui content from the root of the server. My configuration looks like that:

app.use('/', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

However, when I'm trying to access some other route defined, such as let's say "/movies", I'm still seeing the swagger-ui instead of the API response.
Is there any other way of having the swagger-ui docs in the root of the API without affecting all the other routes?

Unsecure curl

I am having some issues on my https site. I have a post request against my api to demonstrate the login endpoint, but as soon as I click the Try it out button and the curl command is executed, the site turns unsecure and the request is cancelled. The automatically generated curl command looks like this: curl -X POST "https://localhost:3000/api/v1/login?username=fasfas&password=sdfasdf" -H "accept: application/json". If I'm not completely mistaken, curl need to fetch a ssl certificate in order to be able to execute the command in a secure way. The alternative being allowing curl to make the request anyway since it shouldn't post towards my production database.

This sounds like a very similar issue, although I've only specified https as my schema in my .json file.

Swagger ui displays paths vendor extensions as a path

If I have:

...
paths:
   x-vendor-extension:
   /pets:
       ...

Shouldn't I only get /pets as a path in the UI? Currently, it displays both x-vendor-extension and /pets.

OAS 2 specifies paths must begin with a slash and 'x-' signals a vendor extension (that I assume would be ignored in the displayed UI).

font file loading fail in Secure Internet Environment

Hi. I use swagger-ui-express very well.

recently. my swagger app not loaded font file ('https://fonts.googleapis.com/css)

because 'indexTemplate.html' file includes 'https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700'

<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">

but it is not loaded in secure internet environment.

Can you include this file in npm?

Use with express.Router()

So I'd like to consolidate all of my swagger config into a library (lib/apidoc.js) and have that library export a Router object that specifies the paths. There's no example in the README and I'm not yet having much luck getting this to work for the UI component.

In my case, I have to expose both the config and the generated HTML. Hoping someone can help me see what I'm missing:

lib/apidoc.json

const express = require('express');
const router = express.Router();  // eslint-disable-line
const swaggerUI = require('swagger-ui-express');
const swaggerDoc = require('swagger-jsdoc');
const apiVersion = require('../../package.json').version;
const config = {
    swaggerDefinition: {
        info: {
            title: 'My Service', // Required
            version: apiVersion, // Required
            description: '...'
        }
    },
    apis: [ './.swagger.js' ] // Path to the docs
};

// The routes below will be "mounted" at /srv/api.
// As a result, the full endpoints will be /srv/api/spec and /srv/api/

// This route works perfectly well
router.route('/spec')
    .get(function(request, response) {
        response.setHeader('Content-Type', 'application/json');
        response.send(swaggerDoc(config));
    });

// This route...not so much.
router.route('/foo')
    .get(swaggerUI.serve, swaggerUI.setup(swaggerDoc(config), true));

module.exports = router;

routes/index.js

const apiDocs = require('./lib/apidoc');

module.exports = function(app) {
    app.use('/srv/api', apiDocs);
}

I've tried a number of variants that haven't worked. This is just the last one. Probably something dumb, but...¯_(ツ)_/¯. I seem to be blind to it.

Would really appreciate any thoughts.

'url' in the swagger options is ignored

in the swaggerOptions the keys 'spec' is always set. So if the 'url' is set as an extra option it is ignored, as the swagger ui ignores 'url' when 'spec' exists.

This means its not possible to get the swagger ui to display the link to the swagger definition as the link to the swagger definition is only shown when 'url' is set and 'spec' is not set....

UI Does not change when the schema has changed

I use this package to merge some docs and show the UI in one endpoint. when one of the docs changed , i call the setup function with the new merged JSON. but the UI does not change.

When something changed , I do this.

 this._setupFunc = swaggerUi.setup(this._schema);
 this._app.use('/', swaggerUi.serve, this.serve.bind(this));

The this.serve function calls this._setupFunc function.

formData parameter with file upload

I have the following parameters on a request:

"parameters": [{ "name": "profileId", "in": "formData", "required": true, "type": "string" }, { "name": "file", "in": "formData", "type": "file", "required": "true" }],

When the request is submitted with the data, the "file" parameter in the form-data is not being sent.
Can you tell me why?

Cannot find indexTemplate.html

I'm using this along with swagger-jsdoc to document my Express endpoints. When I try to start the app, I get the following error:

fs.js:663
  return binding.open(pathModule.toNamespacedPath(path),
                 ^

Error: ENOENT: no such file or directory, open '//indexTemplate.html'
    at Object.fs.openSync (fs.js:663:18)
    at Object.fs.readFileSync (fs.js:568:33)
    at Object.setup (webpack-internal:///197:16:16)
    at eval (webpack-internal:///196:70:82)
    at Object.<anonymous> (/home/matt/code/express-api-documentation/.dist/index.js:2354:1)
    at __webpack_require__ (/home/matt/code/express-api-documentation/.dist/index.js:20:30)
    at eval (webpack-internal:///120:19:16)
    at Object.<anonymous> (/home/matt/code/express-api-documentation/.dist/index.js:1473:1)
    at __webpack_require__ (/home/matt/code/express-api-documentation/.dist/index.js:20:30)
    at /home/matt/code/express-api-documentation/.dist/index.js:63:18

There seems to be something weird causing it to look for //indexTemplate.html instead of some relative/absolute path (i.e., not //foo).
I'm setting up swagger-ui-express like this: (permalink to file in project)

import express from 'express'
import path from 'path'
import swaggerUI from 'swagger-ui-express'
import swaggerJsDoc from 'swagger-jsdoc'
import npmMeta from '../package.json'

const router = express.Router()

const swaggerSpec = swaggerJsDoc({
  swaggerDefinition: {
    info: {
      title: 'Library',
      description: 'Example documentation of Express API',
      version: npmMeta.version,
      license: {
        name: 'Unlicense',
        url: 'http://unlicense.org/UNLICENSE'
      }
    }
  },
  apis: [ `./api/*` ]
})
router.get('/spec.json', (req, res) => {
  res.send(swaggerSpec)
})
router.use('/docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec))

export default router;

I then use that exported router like so: (permalink with context)

import express from 'express'
import swagger from './swagger'

const app = express()
// snip
app.use('/swagger', swagger)
// snip

Full source

Resource/Path Not in Order

The Swagger HTML does not maintain the order that the swagger.json file has in the paths.

For example if I list '/first-path' '/second-path', the swagger HTML randomly orders the two paths in the HTML.

Is there an option or something I'm missing that enforces the order to be maintained?

Default URL is http://petstore.swagger.io

When I run this module it works great with the swagger UI coming up, but the default location it tries to test against is http://petstore.swagger.io. By digging into your module I see you can add a ?url= parameter to the path to make it use whatever path you would like. This has proven to be a big pain for me to do with express.

I have tried to make a redirect rule that will redirect back to the same page it if is missing the ?url parameter and then appending ?url=http%3A%2F%2Flocalhost%3A9090%2F. This is breaking things for swagger when i do that.

Could you change it to default to something like "window.location.origin" and use the ?url= parameter if you want it something custom?

Source map missing

I'm getting this error when the chrome dev tools are opened:
DevTools failed to parse SourceMap

For those files:
swagger-ui-bundle.js.map
swagger-ui-standalone-preset.js.map
swagger-ui.css.map

Can you add the missing static files? Or use other solution like removing the references to those missing file from the code or bundle without the source map option?

Relative path issue.

when I split swagger spec to different json files, it display resolver error.

Errors

Resolver error at paths./students.$ref
Could not resolve reference because of: Tried to resolve a relative URL, without having a basePath. path: './tt.json' basePath: 'undefined'

Retrieve Swagger JSON spec from endpoint instead of static definition

I'm looking for a way to add Swagger documentation for my Express API generated by comments inlined in the code. swagger-jsdoc seems like a cool project to do that, and it serves the documentation generated on an endpoint in the app. I think it'd work very nicely with this project, if I were able to configure swagger-ui-express to use a specific URL instead of a static JSON object as its source. What do you think about it? I can try and send a PR this weekend if you like the idea.

Concat javascript

Any way we could get javascript concatonated in a single file? I had to remove some rate-limiting from my web serverto get all those files to load.

Non position dependent custom swagger options

Maybe this is more of a feature request, but it would be neat to not have to account for the position of the options when declaring them. Also, it's a bit weird to have to set a lot of null parameters if I only want to utilize the custom url option for example; app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, null, null, null, null, 'http://petstore.swagger.io/v2/swagger.json'));

My proposal is to send an object where custom options can be defined in whatever order, or left out if not needed. So in regard to the above example, it would be something like this instead:
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup({'loadUrl': 'http://petstore.swagger.io/v2/swagger.json'}));

setup options not working

In the generated html I am getting

var customOptions = this["undefined"] = {
  "operationsSorter": "alpha",
  "docExpansion": "none"
};

I am using below customization

    const showExplorer = false;
    const suiOptions = {
        operationsSorter: function (a, b) {
            let order = {
                'get': '0',
                'post': '1',
                'put': '2',
                'patch': '3',
                'delete': '4'
            };
            return order[a.get('method')].localeCompare(order[b.get('method')]);
        },
        docExpansion: 'none'
    };
    const customCss = '.swagger-ui .topbar { display: none }';
    app.use(constants.SERVICE_BASE_URI + '/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, showExplorer, suiOptions, customCss));```

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.