2

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.

Michael Lucas
  • 733
  • 1
  • 8
  • 23
  • It looks like, at least in "delegate" mode, the open-api-generator creates a getRequest() method that returns a NativeWebRequest (wrapped in Optional), which appears promising as it has getHeader() methods. I am looking into that now. – Michael Lucas Apr 21 '20 at 15:39

1 Answers1

4

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");
Michael Lucas
  • 733
  • 1
  • 8
  • 23
  • how does this work? isn't the controller a singleton? does this mean that subsequent requests will still have the first request instead of their own ? – aldrin Jul 23 '20 at 06:55
  • 1
    @aldrin as far as I know, Spring manages the injection of NativeWebRequest and other HTTP objects in a threadsafe way. See this answer: https://stackoverflow.com/a/48575275/133782 – Michael Lucas Jan 25 '21 at 13:52