How to open local files in Swagger-UI
Asked Answered
B

20

96

I'm trying to open my self generated swagger specification file my.json with swagger-ui on my local computer.

So I downloaded the latest tag v2.1.8-M1 and extracted the zip. Then I went inside the sub folder dist and copied the file my.json into it. Now I opened the index.html and want to explore my.json. And here the problem begins:

File in windows explorer Enter path to file in bar Will be prefixed by current url and cannot find the file

If I enter a local path, it always will be prefixed by the current url containing the index.html. And therefor I can't open my file. I tried all following combinations without success:

  • my.json leads to file:///D:/swagger-ui/dist/index.html/my.json
  • file:///D:/swagger-ui/dist/my.json leads to file:///D:/swagger-ui/dist/index.html/file:///D:/swagger-ui/dist/my.json
Barong answered 22/5, 2015 at 15:22 Comment(1)
You actually don't need to host your Swagger UI in order to view Swagger spec. I have written an article which explains how you can use online available petstore Swagger UI to view your swagger spec. Check this out - medium.com/@requestly_ext/…Oaxaca
B
4

What works, is to enter a relative path or an absolute without the file://-protocol:

  • ../my.json leads to file:///D:/swagger-ui/dist/index.html/../my.json and works
  • /D:/swagger-ui/dist/my.json leads to file:///D:/swagger-ui/dist/my.json and works

HINT

This answer works with Firefox on Win7. For Chrome-Browser, see comments below:

Barong answered 22/5, 2015 at 15:22 Comment(2)
Chrome needs to be started with --allow-file-access-from-files argument or with --disable-web-security argument to make this hint work.Committeewoman
how do I make it so that the user doesn't need to enable --alow-file-access. I will be sending a .zip file to multiple peopleEnrobe
R
76

I could not get Adam Taras's answer to work (i.e. using the relative path ../my.json).

Here was my solution (pretty quick and painless if you have node installed):

  • With Node, globally install package http-server npm install -g http-server
  • Change directories to where my.json is located, and run the command http-server --cors (CORS has to be enabled for this to work)
  • Open swagger ui (i.e. dist/index.html)
  • Type http://localhost:8080/my.json in input field and click "Explore"
Ruffo answered 11/11, 2015 at 19:16 Comment(6)
This is atrocious design. Why not just make Swagger UI run on a local node server?Cherin
@KennyWorden, because that doesn't work - maybe test next time? Hosting Swagger UI on a local node server works fine, but then if I put in the local path to the API, i.e. "file:///path/to/api.json", the UI auto-appends "localhost:8080/file:///path/to/api.json" - obviously this path doesn't work. I could move the API to the same directory, type in "my.json", but copying the API to the Swagger UI location isn't necessarily "beautiful" either - any variation of this is ugly. It may make you feel better personally, but I'd rather have less steps that work reliably.Ruffo
Thanks. That's exactly what I was missing. The --cors parameter. I used it with a docker image connecting to http-server perfectly. Thanks again.Younker
Well this was a bit of a crash course on how http servers work, but I managed to get it all running. Thanks!Sanitarian
Recommend http-server --cors -a 127.0.0.1 to prevent anyone else on the network from browsing your directory index.Nubianubian
Maybe it could be useful to someone, latest standalone swagger release link for download github.com/swagger-api/swagger-ui/releases/latestChafer
P
35

Use the spec parameter.

Instructions below.

Create spec.js file containing Swagger JSON

Create a new javascript file in the same directory as index.html (/dist/)

Then insert spec variable declaration:

var spec = 

Then paste in the swagger.json file contents after. It does not have to be on the same line as the = sign.

Example:

var spec =

{
    "swagger": "2.0",
    "info": {
        "title": "I love Tex-Mex API",
        "description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
        "version": "1.0.0"
    },
    ...
    }
}

Modify Swagger UI index.html

This is a two-step like Ciara.

Include spec.js

Modify the /dist/index.html file to include the external spec.js file.

 <script src='spec.js' type="text/javascript"></script>

Example:

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <!-- Original file pauses -->
  <!-- Insert external modified swagger.json -->
  <script src='spec.js' type="text/javascript"></script>
  <!-- Original file resumes -->

  <script type="text/javascript">

    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }

Add spec parameter

Modify the SwaggerUi instance to include the spec parameter:

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",
Progress answered 12/7, 2016 at 4:10 Comment(5)
This gives the following error: Finished Loading Resource Information. Rendering Swagger UI...Parisparish
This works nicely without having to mess with npm and keeps the ability to locally host the dist/ folder which is sort of the whole point.Trisomic
still working in january 2021, swagger 3.38.0Selene
does this only work with JSON specs? doesn't seem to work with YAML specs at first glance.Contort
works superb, thxVapor
L
22

In a local directory that contains the file ./docs/specs/openapi.yml that you want to view, you can run the following to start a container and access the spec at http://127.0.0.1:8246.

docker run -t -i -p 8246:8080 -e SWAGGER_JSON=/var/specs/openapi.yml -v $PWD/docs/specs:/var/specs swaggerapi/swagger-ui
Lobworm answered 5/12, 2018 at 12:42 Comment(4)
This worked for me too. Do you know how we can remove the top bar in the swagger UI so it doesnt show the URL location of the swagger file?Amalberga
for people on windows: replace $PWD with %cd%Ashlar
@Amalberga you would need to extend or modify the docker image to do that. A bit involved to explain in a comment.Lobworm
@Ashlar $PWD will also work on Windows when you're in PowerShell.Xanthus
E
20

After a bit of struggle, I found a better solution.

  1. create a directory with name: swagger

    mkdir C:\swagger
    

If you are in Linux, try:

    mkdir /opt/swagger
  1. get swagger-editor with below command:

    git clone https://github.com/swagger-api/swagger-editor.git
    
  2. go into swagger-editor directory that is created now

    cd swagger-editor
    
  3. now get swagger-ui with below command:

    git clone https://github.com/swagger-api/swagger-ui.git
    
  4. now, copy your swagger file, I copied to below path:

    ./swagger-editor/api/swagger/swagger.json
    
  5. all setup is done, run the swagger-edit with below commands

    npm install
    npm run build
    npm start
    
  6. You will be prompted 2 URLs, one of them might look like:

    http://127.0.0.1:3001/
    

    Above is swagger-editor URL

  7. Now browse to:

    http://127.0.0.1:3001/swagger-ui/dist/
    

    Above is swagger-ui URL

Thats all.

You can now browse files from either of swagger-ui or swagger-editor

It will take time to install/build, but once done, you will see great results.

It took roughly 2 days of struggle for me, one-time installation took only about 5 minutes.

Now, on top-right, you can browse to your local file.

best of luck.

Engud answered 26/6, 2017 at 6:59 Comment(2)
Thanks. Just a note. Since we are running under nodejs in this scenario, we don't really read the files from the disk but use the URL, example: 10.0.60.76:3001/swagger-ui/myfile.json (type this not in the URL of the browser, but in the file to open to the left of the Explore button, then click Explore). But I imagine most people just want to use the swagger-ui on the swagger site, then open a disk file on their computer (which would not be a URL).Renaterenato
127.0.0.1:3001/swagger-ui/dist just gives me a lot of redirects until it fails. 127.0.0.1:3001/swagger-ui/dist/index.html works and there I need to paste 127.0.0.1:3001/swagger-ui/dist/api/swagger/swagger.json to Explore field and click the Explore button.Summarize
L
20

Simplest way:

Run npx open-swagger-ui --open <path or URL>

That’ll start a local Web server that has the Swagger UI built in, and will open your browser right to the page, preloaded with the JSON file you specify.

Liquorish answered 14/4, 2022 at 13:59 Comment(5)
100% the easiest way. First time and it worked!Behest
Easy and fast. Underrated answer :pIdeal
Not good enough for us who want to host it for various reasons. For example we require local authentication to access the documentation.Elburt
Anyone knows how to combine the above with CORS?Armenia
Definitely the answer. If I could upvote multiple times I would.Thoroughgoing
L
12

If all you want is just too see the the swagger doc file (say swagger.json) in swagger UI, try open-swagger-ui (is essentially, open "in" swagger ui).

open-swagger-ui ./swagger.json --open
Lyons answered 22/1, 2020 at 6:29 Comment(2)
Thanks! That is probably the easiest option if you just want to visualize your swagger.json fileCusped
This is good, but it's broken for basePathAutomata
B
4

What works, is to enter a relative path or an absolute without the file://-protocol:

  • ../my.json leads to file:///D:/swagger-ui/dist/index.html/../my.json and works
  • /D:/swagger-ui/dist/my.json leads to file:///D:/swagger-ui/dist/my.json and works

HINT

This answer works with Firefox on Win7. For Chrome-Browser, see comments below:

Barong answered 22/5, 2015 at 15:22 Comment(2)
Chrome needs to be started with --allow-file-access-from-files argument or with --disable-web-security argument to make this hint work.Committeewoman
how do I make it so that the user doesn't need to enable --alow-file-access. I will be sending a .zip file to multiple peopleEnrobe
E
4

I managed to load the local swagger.json specification using the following tools for Node.js and this will take hardly 5 minutes to finish

swagger-ui-dist

express

Follow below steps

  1. Create a folder as per your choice and copy your specification swagger.json to the newly created folder
  2. Create a file with the extension .js in my case swagger-ui.js in the same newly created folder and copy and save the following content in the file swagger-ui.js
const express = require('express')
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const app = express()

// this is will load swagger ui
app.use(express.static(pathToSwaggerUi))

// this will serve your swagger.json file using express
app.use(express.static(`${__dirname}`))

// use port of your choice
app.listen(5000)
  1. Install dependencies as npm install express and npm install swagger-ui-dist
  2. Run the express application using the command node swagger-ui.js
  3. Open browser and hit http://localhost:5000, this will load swagger ui with default URL as https://petstore.swagger.io/v2/swagger.json
  4. Now replace the default URL mentioned above with http://localhost:5000/swagger.json and click on the Explore button, this will load swagger specification from a local JSON file

You can use folder name, JSON file name, static public folder to serve swagger.json, port to serve as per your convenience

Eyde answered 18/1, 2021 at 7:29 Comment(0)
A
3

I had that issue and here is much simpler solution:

  • Make a dir (eg: swagger-ui) in your public dir (static path: no route is required) and copy dist from swagger-ui into that directory and open localhost/swagger-ui
  • You will see swagger-ui with default petstore example
  • Replace default petstore url in dist/index.html with your localhost/api-docs or to make it more generalized, replace with this:

    location.protocol+'//' + location.hostname+(location.port ? ':' + location.port: '') + "/api-docs";

  • Hit again localhost/swagger-ui

Voila! You local swagger implementation is ready

Anomalistic answered 14/11, 2015 at 12:33 Comment(0)
P
3

LINUX

I always had issues while trying paths and the spec parameter.

Therefore I went for the online solution that will update automatically the JSON on Swagger without having to reimport.

If you use npm to start your swagger editor you should add a symbolic link of your json file.

cd /path/to/your/swaggerui where index.html is.

ln -s /path/to/your/generated/swagger.json

You may encounter cache problems. The quick way to solve this was to add a token at the end of my url...

window.onload = function() {

var noCache = Math.floor((Math.random() * 1000000) + 1);

// Build a system
const editor = SwaggerEditorBundle({
url: "http://localhost:3001/swagger.json?"+noCache,
  dom_id: '#swagger-editor',
  layout: 'StandaloneLayout',
  presets: [
    SwaggerEditorStandalonePreset
  ]
})

window.editor = editor
}
Pestle answered 18/5, 2017 at 14:10 Comment(1)
Also, need to change SwaggerEditorBundle's url to relative path of swagger.json file.Outvote
A
3

This is not an answer just little update for paragbaxi's answer, so please upvote original answer instead this

paragbaxi's solution works like a charm in 2021

here is entire index.html for latest openapi=3.0.2:

<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
    <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
    <style>
      html
      {
        box-sizing: border-box;
        overflow: -moz-scrollbars-vertical;
        overflow-y: scroll;
      }

      *,
      *:before,
      *:after
      {
        box-sizing: inherit;
      }

      body
      {
        margin:0;
        background: #fafafa;
      }
    </style>
  </head>

  <body>
    <div id="swagger-ui"></div>
    <script src='spec.js' type="text/javascript"></script>
    <script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
    <script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
    <script>
    window.onload = function() {
      // Begin Swagger UI call region
      const ui = SwaggerUIBundle({
        spec: spec,
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout"
      });
      // End Swagger UI call region

      window.ui = ui;
    };
  </script>
  </body>
</html>
Apograph answered 16/4, 2021 at 15:52 Comment(2)
This is not an answer. Simply stating someone´s answer is still valid does not qualify a post as an aswer. Please remove and repost it as comment if needed,Cheju
You're absolutely right. this is not answer. Unfortunately I have not enough reputation to make comments. The reason why I've posted this is that the paragbaxi's code differs from that we have in last (2021) layout of index.html. And I've spend some time to figure out what is where should be changed. I wanted to help anyone who faced the same. If you still think that this should be deleted and posted as comment, could you please publish my code as comment and I will delete mine. (there is no matter for me who posted a code)Apograph
J
2

There is also an official Docker image with Swagger UI, so if you use Docker, this is probably the easiest way to get it to run locally.

Image On DockerHub (documentation links broken): https://hub.docker.com/r/swaggerapi/swagger-ui

Documentation on GitHub: https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/installation.md#docker

If you use docker-compose, you can adapt the following example config:

swagger:
  image: swaggerapi/swagger-ui
  environment:
    - "SWAGGER_JSON=/app/docs/[name of your OpenAPI file]"
  volumes:
    - "./[relative path of your OpenAPI file]:/app/docs"
  ports:
    - "[port you want to assign to the container]:8080"

(Yes, I know this is answer #17 at the time of this writing, but no previous answer has mentioned this Docker image)

Jehoshaphat answered 27/7, 2021 at 8:8 Comment(1)
If you just directly mount your json file to /app/swagger.json in your volumes like ./my-json-file.json:/app/swagger.json then you don't need the environment. sauce: github.com/swagger-api/swagger-ui/blob/master/DockerfileRaja
D
1

My environment,
Firefox 45.9 , Windows 7
swagger-ui ie 3.x

I did the unzip and the petstore comes up fine in a Firefox tab. I then opened a new Firefox tab and went to File > Open File and opened my swagger.json file. The file comes up clean, ie as a file.

I then copied the 'file location' from Firefox ( ie the URL location eg: file:///D:/My%20Applications/Swagger/swagger-ui-master/dist/MySwagger.json ).

I then went back to the swagger UI tab and pasted the file location text into the swagger UI explore window and my swagger came up clean.

Hope this helps.

Deventer answered 15/5, 2017 at 16:43 Comment(0)
S
0

Instead of opening swagger ui as a file - you put into browser file:///D:/swagger-ui/dist/index.html you can: create iis virtual directory which enables browsing and points to D:/swagger-ui

  1. open mmc, add iis services, expand Default Web Site add virtual directory, put alias: swagger-ui, physical path:(your path...) D:/swagger-ui
  2. in mmc in the middle pane double click on "directory browsing"
  3. in mmc in the right pane click "enable"
  4. after that in browser put url to open your local swagger-ui http://localhost/swagger-ui/dist/
  5. now you can use ../my.json if you copied file into dist folder or you can created separate forlder for samples, say D:/swagger-ui/samples and use ../samples/my.json or http://localhost/swagger-ui/samples/my.json
Sabadilla answered 23/7, 2015 at 15:10 Comment(0)
E
0

This is how I worked with local swagger JSON

  1. Have tomcat running in local machine
  2. Download Swagger UI application and unzip it into tomcat's /webapps/swagger folder
  3. Drop local swagger json file inside /webapps/swagger folder of tomcat
  4. Start up tomcat (/bin/sh startup.sh)
  5. Open a browser and navigate to http://localhost:8080/swagger/
  6. type your swagger json file in the Swagger Explore test box and this should render the APIs.

Hope this works for you

Enchantment answered 31/8, 2016 at 8:47 Comment(0)
N
0

With Firefox, I:

  1. Downloaded and unpacked a version of Swagger.IO to C:\Swagger\
  2. Created a folder called Definitions in C:\Swagger\dist
  3. Copied my swagger.json definition file there, and
  4. Entered "Definitions/MyDef.swagger.json" in the Explore box

Be careful of your slash directions!!

It seems you can drill down in folder structure but not up, annoyingly.

Noddy answered 4/6, 2018 at 5:14 Comment(0)
A
0

There is an option to use redoc for that.

Apograph answered 20/4, 2021 at 14:37 Comment(0)
A
0

For spring boot application default url is: http://localhost:8080/swagger-ui/index.html

Archiepiscopal answered 8/12, 2022 at 12:47 Comment(0)
C
0

I've also used the inline OpenApi in the spec parameter as mentioned by @paragbaxy

Here is the simple HTML that worked for me (based on SwaggerUi unpgk):

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="SwaggerUI" />
  <title>SwaggerUI</title>
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/swagger-ui.css" />
</head>

<body>
  <div id="swagger-ui"></div>
  <script src="https://unpkg.com/[email protected]/swagger-ui-bundle.js" crossorigin></script>
  <script>
    window.onload = () => {
      window.ui = SwaggerUIBundle({
        spec = {
          "openapi": "3.0.0",
          "info": {
            "title": "Sample API",
            "description": "Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.",
            "version": "0.1.9"
          },
          "servers": [{
              "url": "http://api.example.com/v1",
              "description": "Optional server description, e.g. Main (production) server"
            },
            {
              "url": "http://staging-api.example.com",
              "description": "Optional server description, e.g. Internal staging server for testing"
            }
          ],
          "paths": {
            "/users": {
              "get": {
                "summary": "Returns a list of users.",
                "description": "Optional extended description in CommonMark or HTML.",
                "responses": {
                  "200": {
                    "description": "A JSON array of user names",
                    "content": {
                      "application/json": {
                        "schema": {
                          "type": "array",
                          "items": {
                            "type": "string"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        dom_id: '#swagger-ui',
      });
    };
  </script>
</body>

</html>

Just replace the spec json with your OpenApi JSON, save the HTML file and open it locally in a browser.

Crownpiece answered 7/10, 2023 at 8:41 Comment(0)
M
-1

Yet another option is to run swagger using docker, you can use this docker image:

https://hub.docker.com/r/madscientist/swagger-ui/

I made this ghetto little BASH script to kill running containers and rebuild, so basically each time you make a change to your spec and want to see it, just run the script. Make sure to put the name of your application in the APP_NAME variable

#!/bin/bash

# Replace my_app with your application name
APP_NAME="my_app"

# Clean up old containers and images
old_containers=$(docker ps -a | grep $APP_NAME | awk '{ print $1 }')
old_images=$(docker images | grep $APP_NAME | awk '{ print $3 }')

if [[ $old_containers ]];
    then
        echo "Stopping old containers: $old_containers"
        docker stop $old_containers
        echo "Removing old containers: $old_containers"
        docker rm $old_containers
fi

if [[ $old_images ]];
    then
        echo "Removing stale images"
        docker rmi $old_images
fi

# Create new image
echo "Creating new image for $APP_NAME"
docker build . -t $APP_NAME

# Run container
echo "Running container with image $APP_NAME"
docker run -d --name $APP_NAME -p 8888:8888 $APP_NAME
echo "Check out your swaggery goodness here:

http://localhost:8888/swagger-ui/?url=http://localhost:8888/swagger-ui/swagger.yaml"
Mccall answered 17/2, 2017 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.