Reputation: 2999
I am currently adding swagger to an old project and I would like to add a header to all requests.
The application has a filter that checks if your app version is high enough and thus requires the clients to send in a version
header.
Is it possible to add this to all requests or do I have to rewrite all endpoints to have this header parameter(there is a lot of them). Would be really nice to have a global header parameter.
Should be added that I would like to do this in Java and not change the json/yaml directly
Upvotes: 3
Views: 9600
Reputation: 10142
You can add global operational parameters in your Docket
configuration as done in last line - .globalOperationParameters(operationParameters())
,
I am showing broader configuration but your focus for this question should be only last line.
@Bean
public Docket swaggerPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(PathSelectors.any())
.apis(Predicates.or(
RequestHandlerSelectors
.basePackage(....),
RequestHandlerSelectors
.basePackage(....)))
.build().directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.apiInfo(apiInfo())
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Arrays.asList(securityContext()))
.globalOperationParameters(operationParameters());
}
private List<Parameter> operationParameters() {
List<Parameter> headers = new ArrayList<>();
headers.add(new ParameterBuilder().name("HEADER_1")
.description("HEADER_1 DESC")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build());
headers.add(new ParameterBuilder().name("HEADER_2")
.description("HEADER_2 DESC")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).defaultValue("0").build());
return headers;
}
As illustrated, default value can also be provided. Also, these two headers will be visible on Swagger UI as text fields & values can be entered manually for each request.
Upvotes: 7