Home Ask Login Register

Developers Planet

Your answer is one click away!

Mattan February 2016

Swagger Java common header

I have a REST API server implemented with Jersey2.0 and integrated with Swagger to automate docs and client side applications.

We have our own authentication header (X-Auth-Token) which should be applied to all requests in order to use them (Beside the login request that retrieves the token if credentials are correct).

Right now I need to manually add the the token as ApiImplicitParam annotation to each of the requests in order for the generated docs to include it:

@ApiImplicitParams({@ApiImplicitParam(name = AuthFilter.AUTHORIZATION_PROPERTY, value = "Authorization token", required = true, dataType = "string", paramType = "header")})

I don't want to hardcode the UI code to add the header itself, as I believe it violated the API encapsulation provided by swagger.json. The server definition should provide all the details necessary for the generated docs.

Is there a way to define a custom default annotation for all requests in Swagger? Or alternatively use some kind of Filter to achieve it?


Cássio Mazzochi Molin February 2016

A quick look at the annotations

The ApiImplicitParam and ApiImplicitParams annotations are defined as following:

public @interface ApiImplicitParam

public @interface ApiImplicitParams

Please note the @Target(value=METHOD). It means these annotations only can be applied to methods.

For more details, check the documentation.

What Swagger UI can do for you

In Swagger UI version 2.1.4 released on 6th January 2016 (the most recent version when this answer was written), you can have an API key:

Swagger UI page header with API key

Have a look at the index.html. The default implementation sends the API key as a query parameter:

function addApiKeyAuthorization(){
    var key = encodeURIComponent($('#input_apiKey')[0].value);
    if(key && key.trim() != "") {
        var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
        window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
        log("added key " + key);

But you can

Post Status

Asked in February 2016
Viewed 1,135 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life