user384729
user384729

Reputation: 403

How do you change swagger's path with Jersey and BeanConfig?

Is there any way of having swagger.json sitting somewhere else than the default location (/swagger.json)? Right now it's always deployed to http://localhost:8080/swagger.json, I'd like to have it at http://localhost:8080/api-docs/swagger.json

The setup guide isn't much of a help. All it says is

swagger.api.basepath should point to the context root of your API. This defers from server to server and how you configured your JAX-RS application

but that's for servlet config and I'm not even sure if that'd do what I want.

BeanConfig has a basePath property, but that's purely informational and changing it doesn't have any effect on the actual location.

Upvotes: 2

Views: 3162

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209012

The BeanConfig base path, you don't want to change. That is what Swagger uses to create the URLs for your resource endpoints in the swagger.json.

What you do want to change is the path for resource class that serves up the swagger.json. This will either be ApiListingResource or ApiListingResourceJSON. In the majority of cases, it will most likely be the former.

To change the path, what we need to do is register it differently from how it was normally registered, as the @Path annotation values on the resource class is /. So if we register like any other resource class, it will always be the same as the root path to our Jersey application.

Jersey has an API that allows us to build resources programmatically. So we can build a resource from the ApiListingResource and just change the path

final Resource.Builder builder = Resource.builder(ApiListingResource.class);
// note, this path will be relative your base path of your Jersey app
builder.path("api-docs");
final Resource apiListingResource = builder.build();

Then just register the Resource with your ResourceConfig.

ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.registerResources(apiListingResource);

One thing you need to be sure not to do, is disable the SwaggerSerializers, which is used to serialize the Swagger object to the swagger.json. For instance if you registered swagger with Jersey, by scanning the io.swagger.jaxrs.listing package, both the ApiListingResource and the SwaggerSerializers are in that package, so both of them would have been registered. In our case, we should take out this package from the list of packages to scan, and just individually register the SwahggerSerializers

resourceConfig.register(SwaggerSerializers.class);

Upvotes: 3

Related Questions