Search code examples
node.jsjsonexpressswaggerswagger-ui

Swagger UI can't read referenced JSON


So I am creating an API using express, cors and sequelizer. Now I want my API do have a decent documentation and found Swagger UI to be very useful for this.

To my issue: Since my database is not just one table and the routes are more complicated I wanted to separate the JSON into several files for a better overview. Now the reference I try to use in the index.json just doesn't work. It just seems like info.json won't even be touched.

Here you see my setup of Swagger UI at the beginnig of my node index file:

const express = require("express");
const cors = require("cors");
const app = express();
const db = require("./app/models");
const swaggerDocument = require("./app/swagger/index.json");
const swaggerUi = require("swagger-ui-express");

const swaggerOptions = {
    swaggerOptions: {
        validatorUrl: null
    }
};

app.use("/docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument, swaggerOptions));

./app/swagger/index.json looks like this:

{
    "swagger": "2.0",
    "info": {
        "$ref": "info.json"
    },
    "consumes": [
        "application/json"
    ],
    "produces": [
        "application/json"
    ]
}

and the referenced info.json being in the same folder as index.json looks like this:

{
    "title": "App",
    "version": "0.1",
    "description": "App API Documentation",
    "contact": {
        "name": "My Name",
        "url": "foo.bar"
    },
    "servers": [
        "http://localhost:8000"
    ]
}

In case it is useful: I run everything on docker-compose.


Solution

  • The info object does not support $ref. The content of the info object must be specified inline.

    Also, OpenAPI 2.0 (swagger: '2.0') does not support servers, it uses host + basePath + schemes instead. These keys must be in the root level of the spec. See API Host and Base Path.

    // ./app/swagger/index.json
    
    {
        "swagger": "2.0",
        "info": {
            "title": "App",
            "version": "0.1",
            "description": "App API Documentation",
            ...
        },
    
        "host": "localhost:8000",
        "schemes": ["http"],
        ...
    }