Swagger UI - reading JSON specs from editor into UI without hosting - swagger

I'm attempting to document my API using Swagger by writing the documentation in the Swagger editor and then loading it into the Swagger UI. I used the editor and downloaded my JSON file and then changed the /dist/index.html file within the UI to point to my local file using:
var spec = "file:///Users/user1/Desktop/swagger.json";
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "http://petstore.swagger.io/v2/swagger.json";
}
// Pre load translate...
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
url: url,
spec: spec,
The only thing I changed within the file is the use of the spec var to point to my JSON file, however when I open the UI, it displays a blank UI page with the message "Finished Loading Resource Information. Rendering Swagger UI..." I would just like to display the documentation I created in the editor in the UI without having to host the specs, is there something I'm missing?

Accordign to the Documentation, spec value must be an JSON Object, so you have to do something like:
window.swaggerUi = new SwaggerUi({
spec: JSON.parse('{ "swagger": "2.0", ...')
where
{ "swagger": "2.0", ...
is the content for your file:///Users/user1/Desktop/swagger.json file

Related

Using rails asset in javascript

I'm using rails to build a site, and I want to embed a swagger doc in one of the pages. The swagger yaml file is stored in /app/assets/myfile.yaml. In the swagger embed code (javascript) I've tried a variety of approaches:
// in myswagger.html.erb
window.onload = function() {
const ui = SwaggerUIBundle({
url: "<%= asset_path('myfile.yaml') %>",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
]
})
}
I've also tried a bare path to /app/assets/myfile.yaml, document_path('myfile.yaml'), etc. But every time we end up with Fetch error Not Found /swagger.yaml.
What's the proper way to access this file and get it embedded in the javascript?
fast answer:
put the file yaml in your public folder
otherwise check what is generated at the browser level, by inspecting the page

Changing swagger-ui server variable at runtime

Using an openapi v3 configuration I have a server variable called 'hostname' that is used to build the url, like:
...
servers:
- url: http://{hostname}/api
variables:
hostname:
"default": "some default here"
....
At runtime I'd like to be able to change the 'hostname' server variable. I've found the UI element on the page,
<input type="text" value="some default here" data-variable="hostname">
Changing the variable by editing the input field works fine, but changing the input field via jQuery isn't working, even when triggering the "change" event after setting the value, the value reverts when expanding one of the api sections. I also tried triggering the keyup/keydown and focusin/focusout events to better simulate how a user would change the field.
Is there a more swagger-ui approach to changing this value through an exposed call? I've looked through window.ui but its kind of cryptic.
I have an api.yaml file hosted on different IoT devices. Each device will have a different hostname based on its configuration. When the page is loaded I'm trying to use javascript to set the 'hostname' server variable to be window.location.hostname, for example via javascript.
You can simply specify a relative server url – it will be resolved relative to the location of the OpenAPI definition file.
For example, if you have
servers:
- url: /api
and the API definition file is at
http://foobar/spec/api.yaml
then the base url for API calls will be resolved to
http://foobar/api
You can alter the spec json before it render by writing a plugin
const ui = SwaggerUI({
// ...
plugins: [
// add a plugin to alter spec before it rendered
{
statePlugins: {
spec: {
wrapActions: {
updateJsonSpec: function(oriAction, system) {
return (spec) => {
// change spec.servers here to add new entry, use concat to put it as the first & default one
spec.servers = [{url: someDynamicUrlInRuntime}].concat(spec.servers || [])
return oriAction(spec)
}
}
}
}
}
}
]
// ...
})
Adapting the answer from nevermind for use with SwaggerUIBundle as used in the index.html from swagger-ui:
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
// Custom plugin that replaces the server list with the current url
function() {
return {
statePlugins: {
spec: {
wrapActions: {
updateJsonSpec: function(oriAction, system) {
return (spec) => {
spec.servers = [{url: window.location.origin}]
return oriAction(spec)
}
}
}
}
}
}
}
],
This way the index.html can be served from the backend service itself and will refer only on its own url.

Change default API spec URL in Swagger UI

I'm using the Swagger Editor Docker image for defining my API specification and generate a nodejs server to run as stub api and serve the documentation for my API spec.
I would like to know if it is possible to change the default URL to my own in order to present my spec when I open the page, and how I would do that.
For instance, I would like to change the default address to http://localhost:8080/spec
If I understand correctly, you used Swagger Codegen to generate a Node.js server. Now when you npm start and open Swagger UI, you want the input box (the spec URL) to display http://localhost:8080/spec instead of http://localhost/api-docs.
To change the path the .yaml spec is served from, edit your index.js as follows:
// 1 - add swaggerUi options
var uiOptions = {
apiDocs: '/spec' // <-- override the default /api-docs
};
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
...
// 2 - pass these options to swaggerUi
app.use(middleware.swaggerUi(uiOptions));
The port number is specified by the serverPort variable in index.js:
var serverPort = 8080;

How to access swagger yaml defined objects from javascript

I used Swagger Yaml to describe an endpoint and generate the mock server. The existing endpoint (that I'm mocking) doesn't follow RESTful principles 100%, so I simply want to overwrite the response that is returned by the mock server. The simple server code is shown below:
var swagger = require('swagger-server');
var server = swagger('map-cache.yaml');
var port = 7072;
server.post('/map-qa_trunk/v2/getData', function(req, res, next) {
var foo = {
err : 123,
msg : "error message"
};
res.json(foo);
});
server.listen(port, function() {
console.log('Map Cache Mock Server is now running at http://localhost:' + port);
});
In the Yaml definition, there is an object defined called MapResponseData, how do I create an instance of this object so that I can populate it as needed and return in the res.json()? Something similar to below:
var response = getMapResponseData(); // don't know what this call should be
response.fieldA = 123;
res.json(response);
I am guessing this should be possible, since Swagger parsed the YAML file and is aware of all definitions that were specified.
Try outputting the request object to console.log to see if you can find reference to the swagger definition. Another option would be to pull the parsed swagger definition from the yaml file (using js-yaml for example) and extracting from there.
However, my best advice is to use swagger-tools instead of swagger-server. The swagger-server package is alpha version and has fewer downloads, revisions, and users than swagger-tools. Benefit of swagger-tools is that it will be actively maintained and there is a larger community that can support you. To convert your project to swagger-tools, use swagger.io > Swagger Editor > Online Editor > Paste yaml in left pane > Generate Server > Node.js
In swagger-tools the entire Swagger Yaml definition is contained in each request object:
req.swagger.swaggerObject
and you can pull the response object definitions from that as needed.

How to publish swagger editor left window as documentation

I want to publish the right side panel of the swagger editor.
Currently, the team has to share the yaml file and each user has to copy & paste the text into the swagger editor to view the right panel rendering.
Is there a way to publish the content to html so that a page would look like the right panel ?
Example swagger editor windown with formated look on the right:
http://azimi.me/presentations/building-swagger-editor/images/swagger-ui.png
AFAIK there is no way to publish it right from the swagger editor but you can use swagger-ui. All you need is to
download swagger-ui
host it on a web server that is accessible for your team
save your swagger documentation code to a new file of any filename and host it on your web server, too.
tell swagger-ui which documentation file it shall load.
For the last step look for the following piece of code within the swagger-ui's index.html:
$(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";
}
Replace the value of line url = "http://petstore.swagger.io/v2/swagger.json"; to point to the swagger documentation file you uploaded.

Resources