Search code examples
javaspring-bootswagger-uispringdoc

How to inject a custom header whenever a request is sent from Swagger UI?


I have a situation when I would like to hard-code a request header called test-header which will store simple JSON data {"username":"swagger", "email":"dummy@email"}. So the users who will use Swagger UI to make requests won't need to add this data manually, it will always be automatically added to each request sent from Swagger UI.

I am using org.springdoc with Spring Boot v3. And currently I just have simple OpenAPI bean:

@Bean
public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
    return new OpenAPI()
            .info(new Info().title("Person API").version(appVersion)
                    .license(new License().name("Apache 2.0").url("http://springdoc.org")));
};

Is there a possibility to add it somehow to it? Or am I fated to use a filter/interceptor?


Solution

  • Yes, it's possible to pass a custom header with some default value through Swagger UI. You can use the below code snippet to customize OpenAPI -

    @Bean
    public OpenApiCustomizer getCustomizer() {
        ObjectSchema myCustomSchema = new ObjectSchema();
        myCustomSchema.addProperty("username", new Schema<>().type("string")._default("swagger"));
        myCustomSchema.addProperty("email", new Schema<>().type("string")._default("dummy@email"));
    
        return openApi -> openApi.getPaths().values().stream()
                .flatMap(pathItem -> pathItem.readOperations().stream())
                .forEach(operation -> 
                    operation.addParametersItem(
                            new HeaderParameter()
                                    .name("test-header")
                                    .required(false)
                                    .schema(myCustomSchema).explode(true)
                                    .style(Parameter.StyleEnum.SIMPLE)
                    )
                );
    }
    

    This will produce your header's value in the controller as username=swagger,email=dummy@email.

    But I'll suggest if you have to pass a JSON as a header then pass it in stringified, and parse it to an object in your controller. For string type header, OpenAPI can be customized as -

     @Bean
    public OpenApiCustomizer getCustomizer() {
        return openApi -> openApi.getPaths().values().stream()
                .flatMap(pathItem -> pathItem.readOperations().stream())
                .forEach(operation -> operation
                        .addParametersItem(
                                new HeaderParameter()
                                        .name("test-header")
                                        .required(false)
                                        .schema(new Schema().type("string")._default("{\"username\":\"swagger\", \"email\":\"dummy@email\"}"))
                        ));
    }
    

    Please upvote if it helps.