Sometimes we build APIs which have to deal with very expensive responses in terms of performance or bandwith, for example, if we offer an endpoint which download a pdf document or deliver a huge amount of data.

In those cases, the consumers of our API would implement a caching mechanism to avoid performing every time a new request. But how do they know how oft they need to update the cached content?

ETag purpose

The Etag, as well known as Entity Tag, is part of the HTTP protocol and is basically a value which correponds with the current status of a requested resource.

When an API receives a request, it will calculate a hash value based on the response to be delivered. This hash value will be delivered in a HTTP header known as ETag.

The reason why ETag is a very useful tool is because it allows consumers to perform a better management of the cache on the consumer side. They may cache the response to increase performance but at some point, the cache will be cleared and the a new call has to be made to the server again. 

Consumers can use the ETag value and send it on future requests using the header “If-None-Match”. The API (or server) will process the request and calculate the ETag again, but this time it will be compared with the value sent by the client. If it matches, means that the hashhas not been changed, or in other words, the response is the same, therefore the API will deliver a HTTP 304 Not Modified.

This way, no response will be sent back to the client and some bandwith can be saved as well. The client will update the cache as it knows the response is still valid.

Configuration in SpringBoot applications

Since SpringBoot is one of the most used frameworks to develop APIs nowadays, I will show you how easy is to configure the ETag.

The only thing you need to do is to declare the following Bean in your application:

@Bean
public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
    return new ShallowEtagHeaderFilter();
}

From this moment, your API will calculate the ETag for every response and send the value back in the HttpHeaders.

To see it in action, I developed a very basic endpoint /ping which returns “pong” as response. Let’s see what happen when we perform the call:

As you can see, we’ve got a new header “ETag”. To check if it is working properly, let’s make the same call as before but now sending that value in the “If-None-Match” header:

Voilà, the API just returned the expected http status code 304 Not Modified.

And that was all! If you find is useful do not hesitate to share the post!

Find the source code in my Github repository.

See you!