Last Updated: June 11, 2021
·
1.771K
· imadjomaa

HTTP ETag - API Cache Handling

If you offer an API and encourage clients to cache data, sending an HTTP ETag is the way to go. An ETag is a unique identifier returned in the HTTP header response (if provided) specific to the content that is to be returned. If the content changes, a new ETag is assigned. What this means is, a simple HTTP header request can be made to quickly know whether the content has changed or not, without the need for your servers to send full responses. Thus, you can save on bandwidth, caching for your clients becomes more efficient, and it is easy to implement.

How it Works

Client makes request, server provides full response with ETag in the header:
...
ETag: "uniqueidentifier"
...

Client makes subsequent request to update cache if need-be. Client provides header information:
...
If-None-Match: "uniqueidentifierhere"
...

Where the 'uniqueidentifierhere' is the ETag the client stored from the previous response. The server should now compare the ETags, if they are different, return a full response, otherwise, return a 304 HTTP status, indicating the content has not changed, and thus, the client's cache is not stale.