Define Global Request Parameters in Spring Boot 3 using Swagger/Open Api 3

596 Views Asked by At

I am using Spring Boot 3 with Swagger/Open Api 3 (springdoc-openapi-starter-webmvc-ui, version 2.20)

In every API request I make I need to specify a request header "X-example=value". You can find below 2 examples of requests.

@Operation(summary="GET of a Single Asset",
    parameters= {@Parameter(name="X-example", in=ParameterIn.HEADER, required=true)})
    @GetMapping("/assets/{id}")
    public ResponseEntity<DlAsset> getAssetById(@PathVariable("id") String id) {

\\\

@Operation(summary="POST of an Asset",
    parameters= {@Parameter(name="X-example", in=ParameterIn.HEADER, required=true)})
    @PostMapping("/assets")
    public ResponseEntity<String> createAsset(@Valid @RequestBody @Validated(Create.class) AssetDTO asset) {

I have 10+ requests though and I would like to specify "X-example" only once, globally. I searched several times here but I only seem to find cases for prior versions of Swagger. Please let me know if you have suggestions to better reframe the question. Thanks!

1

There are 1 best solutions below

0
On

You can do this with OperationCustomizer. Whichever backend framework is used, Swagger receives a common json format and renders it.

@Component
public class CustomOperationCustomizer implements OperationCustomizer {

    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        generateGlobalRequestHeader(operation);
        return operation;
    }

    private void generateGlobalRequestHeader(Operation operation) {
        List<Parameter> parameters = operation.getParameters();
        if (parameters == null) {
            parameters = new ArrayList<>();
        }
        var parameter = new Parameter();
        var schema = new Schema<>();
        schema.setType("string");
        parameter.setName("X-example");
        parameter.setIn("header");
        parameter.setRequired(false);
        parameter.set$ref("");
        parameter.setDescription(" ");
        parameter.setDeprecated(false);
        parameter.setSchema(schema);
        parameters.add(parameter);
    }
}

    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("v1")
                .pathsToMatch("/**")
                .addOperationCustomizer(operationCustomizer)
                .build();
    }