Skip to content

Instantly share code, notes, and snippets.

@hareeqi
Last active December 13, 2018 14:29
Show Gist options
  • Save hareeqi/c9496288cfccf52342930874ac9670d3 to your computer and use it in GitHub Desktop.
Save hareeqi/c9496288cfccf52342930874ac9670d3 to your computer and use it in GitHub Desktop.
dynamic host for swagger ui 3.x
// not the most elgant way but it works
// in the console post the function below and call changeSwagger("http","localhost:5050","/my_path/)
function changeSwagger (scheme,host,path) {
var newspec = ui.spec().toJSON().resolved
newspec.scheme = [scheme] || newspec.scheme
newspec.host = host || newspec.host
newspec.basePath = path || newspec.basePath
ui.getStore().dispatch({type:'set_scheme',payload: {scheme: newspec.scheme[0]}})
ui.getStore().dispatch({type:'spec_update_resolved',payload:newspec})
}
@ukiome
Copy link

ukiome commented May 9, 2017

Thanks!

@zhimoda
Copy link

zhimoda commented May 11, 2017

Thank you very much for the effort. It seems to not work with comments in the json spec (lines leading with"#"). I get the following error:
Uncaught SyntaxError: Unexpected token # in JSON at position 0 at JSON.parse (<anonymous>)
I suppose that many swagger specs will have comments right at the start like in my case. Any ideas how to deal with that? I'm not that fit with Javascript unfortunately.

Also, is there a hook the changeSwagger function can be called at so that after swagger ui loaded completely the function is called automatically. I fiddled a bit but could not find anything promising.

@hareeqi
Copy link
Author

hareeqi commented May 11, 2017

regarding the hook, i made this where you just can change the host in the url and it works. you can check the source to see the inelegant hook.

http://hareeqi.com/swagger/?host=http://localhost/path&url=http://petstore.swagger.io/v2/swagger.json

@hareeqi
Copy link
Author

hareeqi commented May 11, 2017

I updated the gist, it now should handle the comments you referred to !

@cdjones32
Copy link

Thankyou for this... It was almost exactly what I needed. I modified it a little so that Microservices or similar that host the UI themselves can automatically correct the Scheme, host, port to reflect where they are currently being accessed from, without the application/spec needing to know.

It just polls until it finds the spec loaded and uses the URL the browser has loaded to reset the spec.

https://gist.github.com/cdjones32/251afd18b869578f9ea6dcaeb6526ff0

@marcocamacho
Copy link

It does not seem to work for openapi 3, is there any way to do it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment