How to embed Swagger UI into a webpage? Basically I want an API endpoint test environment to embed into my webpage.
Asked
Active
Viewed 2.4k times
1 Answers
65
The answer depends on whether you have a plain web page you edit directly, or use a framework like Node.js or React. For simplicity, I'll assume the former.
Download (or clone) the Swagger UI repository. You'll need the following files from the dist
folder:
swagger-ui.css
swagger-ui-bundle.js
swagger-ui-standalone-preset.js
In the <head>
section of your web page, add:
<link rel="stylesheet" type="text/css" href="swagger-ui.css">
Inside the <body>
, add:
<div id="swagger-ui"></div>
<script src="swagger-ui-bundle.js"></script>
<script src="swagger-ui-standalone-preset.js"></script>
<script>
window.onload = function() {
const ui = SwaggerUIBundle({
url: "https://yourserver.com/path/to/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
]
})
window.ui = ui
}
</script>
<div id="swagger-ui"></div>
is the DOM node inside which Swagger UI will be rendered. The SwaggerUIBundle
constructor initializes Swagger UI. This is where you specify your spec URL and other parameters.

Helen
- 87,344
- 17
- 243
- 314
-
Everything works fine now. the url is only works for ..../something.json kind of urls. I have a url gives same swagger response but it is not something like /something.json. it do not ends as .json. – Akalanka Hewawasam Sep 15 '17 at 14:20
-
Hi Helen. What would the answer be in the case of a framework like Node? – Peter May 22 '18 at 17:26
-
@Peter You can use Swagger UI npm module - either [swagger-ui](https://www.npmjs.com/package/swagger-ui) (with regular dependencies) or [swagger-ui-dist](https://www.npmjs.com/package/swagger-ui-dist) (dependency-free). – Helen May 22 '18 at 17:32
-
@Helen I did that for a ruby based slate client , I added these things in the layout.erb but I saw no changes in the rendered website can you help – Saurabh Kumar Jun 24 '20 at 18:40
-
@luG_0 please [ask a new question](/questions/ask) and post your code. – Helen Jun 24 '20 at 19:01
-
@Helen I did that here https://stackoverflow.com/questions/62562208/integrating-swagger-ui-to-my-a-slate-generated-website – Saurabh Kumar Jun 24 '20 at 19:29
-
@Helen, This sounds similar to my question. Could u please help me with this question [Change Swagger index.html logo and header contents](https://stackoverflow.com/questions/66704031/change-swagger-index-html-logo-and-header-contents)? – Avinash Mar 23 '21 at 10:34
-
For anyone wondering, the code above also works fine with a .yaml file in the SwaggerUIBundle 'url' parameter – Miiite Jul 06 '21 at 16:19