Hadi Rasouli
Hadi Rasouli

Reputation: 2037

change swagger base path in spring mvc project

I have configured Swagger in my Spring MVC project.

In web.xml i have used /rest/* for servlet-mapping :

 <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

I can access swagger api-doc with url below and every thing is ok:

http://localhost:8080/rest/v2/api-docs

But problem is accessing api with swagger-ul. Swagger uses http://localhost:8080/ (in my localhost) to access API.

I try to create swagger.properties file to change base path but did not work. ('http://www.3pillarglobal.com/insights/restful-api-documentation-using-swagger-and-spring-mvc')

enter image description here

Swagger-ui works fine when i change /rest/* to /* but for reasons i cant do this.

How can i change swagger base path to make it work fine?

Upvotes: 0

Views: 5410

Answers (2)

Dilip Krishnan
Dilip Krishnan

Reputation: 5487

First off make sure you're using the lates version of springfox (2.4.0 at the time of this writing). I noticed the link has references to a very old version springfox.

Once you've updated you can use the docket to specify a pathMapping.

....
docket.pathMapping("/rest")
...

Upvotes: 3

momonari8
momonari8

Reputation: 116

If you have Swagger working already under localhost:8080/rest/ I think the only thing missing in your case is that you can either open swagger-ui index.html file, look for the url parameter and change it to whatever url you have that exposes the Swagger definition:

url = "http://localhost:8080/rest/v2/api-docs/swagger.json";

or be sure that whenever the swagger-ui index.html is called, it has something like this:

http://localhost:8080/swagger-ui/index.html?url=/rest/v2/api-docs/swagger.json

Now, if you want to change the path where the Swagger definition url is exposed, you can create a class that extends from ApiListingResource and override the Path like so:

@Path("/rest/v2/api-docs/swagger.{type:json|yaml}")
public class UMSApiListingResource extends ApiListingResource {
}

Note: I'm using RestEasy not Spring MVC though but it should be pretty similar.

Upvotes: 1

Related Questions