Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve unspec'd headers with openapi-generator (spring)

For our REST APIs, we have certain HTTP Request headers which will be set by infrastructure components, and should not be published to consumers in the OpenAPI spec.

In the Spring Web based implementation code that we build (implementing the openapi-generator's generated interfaces), what is the right way to retrieve something like this from the HTTP Request? For example, a header which is not specified on the interface.

I do not see any options in the openapi-generator itself to add the HttpServletRequest as a parameter to the generated methods. I am hoping there is a more generic way to get a handle to it in Spring / Spring Web.

like image 763
Michael Lucas Avatar asked Dec 09 '25 17:12

Michael Lucas


1 Answers

Okay, so this turns out to be pretty simple and elegant using the open-api-generator's generated Spring code, at least in the "delegate" pattern that I am using.

The Delegate class creates a getRequest() method which you simply override like so:

private final NativeWebRequest nativeWebRequest;

@Override
public Optional<NativeWebRequest> getRequest() {
    return Optional.ofNullable(nativeWebRequest);
}

You may have to add the NativeWebRequest to your constructor or make it @Autowired. (We are using lombok to generate constructor.)

Then in your API method you can just do something like:

String headerValue = getRequest().get().getHeader("my-header-name");
like image 144
Michael Lucas Avatar answered Dec 11 '25 12:12

Michael Lucas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!