Home > Software engineering >  Adding custom request header to every API in spring boot
Adding custom request header to every API in spring boot

Time:06-17

I am trying to add custom request header to every API I can do it by adding a piece of code to every API

`public ResponseDTO setNames(@RequestHeader(value="my-header",required = false HttpServletRequest httpServletRequest) throws Exception {}`

But I want this to be done automatically like we have authorisation header by default when we create a new API.How can this be done can anyone tell me a good solution

enter image description here

CodePudding user response:

You can use the following if you are using springdoc-openapi

@Configuration
class CustomizeSpringDoc {
    @Bean
    fun publicApi(): GroupedOpenApi {
        return GroupedOpenApi.builder()
            .group("add-auth-header")
            .addOperationCustomizer { operation, handlerMethod ->
                operation.parameters.add(
                    HeaderParameter()
                        .name("Authorization")
                        .description("Access Token")
                )
                operation
            }
            .build()
    }
}

If you are using spring-fox, you can refer back to the below link, globalRequestParameters: http://springfox.github.io/springfox/docs/current/#quick-start-guides

CodePudding user response:

You can make use of OpenAPI specification (previously Swagger specification) in your Spring-boot project, where in , you define your APIs along with Request/Response headers as well as any error model you may want to return or any other custom field you want to capture!

By defining, you will have privilege of mentioning attributes such as required, minLength, maxLength etc

The openAPI plugin will take care of rest of the things!

You may refer these links to have a glance!

https://www.javainuse.com/spring/boot_swagger3

https://www.baeldung.com/spring-rest-openapi-documentation

  • Related