Skip to content

Commit

Permalink
Add the API-Version HTTP header to every response, with the version n…
Browse files Browse the repository at this point in the history
…umber provided as a property or environment variable.
  • Loading branch information
arucard21 committed Nov 15, 2024
1 parent 0fb40ec commit 1ed57cc
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 2 deletions.
3 changes: 1 addition & 2 deletions examples/nlgov-adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ API-20 Yes
API-48 Yes
API-51 No CORS policy is invalid
API-56 Yes
API-57 No API-Version header not found
API-57 Yes

Validation failed
```
There is currently nothing configured for CORS in the API so it is expected to fail that test.
The API-Version header is currently only documented in the OpenAPI Specification but it is not yet returned by the API. This can be easily fixed with a JAX-RS filter that adds this header to every response.
1 change: 1 addition & 0 deletions examples/nlgov-adr/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ application{
bootRun {
environment "server.port", "8888"
environment "SIMPLYRESTFUL_URI_HTTP_HEADER", "xoriginalurl"
environment "API_VERSION" "0.0.1"
}

dependencies {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package example.nlgov_adr;

import java.io.IOException;

import jakarta.inject.Named;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;

/**
* Add an HTTP header named "API-Version" to every response.
*
* It contains the version of the API which can be defined in a property or
* environment variable called "API_VERSION".
*/
@Named
public class ApiVersionFilter implements ContainerResponseFilter {
public static final String API_VERSION_HTTP_HEADER_NAME = "API-Version";
public static final String API_VERSION_ENV_NAME = "API_VERSION";

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String apiVersion = getApiVersion();
if(apiVersion != null) {
responseContext.getHeaders().add(API_VERSION_HTTP_HEADER_NAME, apiVersion);
}
}

private String getApiVersion() {
String apiVersion = System.getProperty(API_VERSION_ENV_NAME);
if (apiVersion == null) {
apiVersion = System.getenv(API_VERSION_ENV_NAME);
}
return apiVersion;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
public class ExampleResourceConfig extends ResourceConfig {
public ExampleResourceConfig() {
register(ExampleWebResource.class);
register(ApiVersionFilter.class);
property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
}

0 comments on commit 1ed57cc

Please sign in to comment.