ETags (“If-None-Match”) provide a simple method of saving bandwidth, by checking whether the rates have been updated since your last request.
If the data have not changed since your previous request, you can fallback to a cached copy, and your API response will be under 0.2kb (instead of the standard 2–4kb response). If the rates have changed, you'll receive the latest data as usual.
It's easier than it sounds - here's a step-by-step guide to prove it!
From the article on Etags:
An ETag ["Entity Tag"] is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource content at that URL ever changes, a new and different ETag is assigned. Used in this manner ETags are similar to fingerprints, and they can be quickly compared to determine if two versions of a resource are the same or not.
-- Wikipedia
1. Store the latest API response
Each time you make a request to the Open Exchange Rates API, the HTTP response headers will include an ETag
and a Date
.
The Etag
is a unique identifier for the data returned in the response, and the Date
is the time at which the data was last modified.
Example:
Date: Thu, 20 Dec 2012 14:48:28 GMT
ETag: "4e6acdd9fea30c21d9bdf1925afbf846"
After receiving your API response, cache the entire response somewhere (e.g. to a file, database or in memory), along with the values for the ETag
and Date
headers.
2. Add the "If-None-Match" header
Next time you make a request to the same API URL, add the If-None-Match
header, with the value set to the ETag
you grabbed from the previous request, wrapped in double quotation '"' marks.
You also need to send an If-Modified-Since
header, which will be the Date
value from the last successful request.
Using the example above, your two request headers would look like this:
If-None-Match: "4e6acdd9fea30c21d9bdf1925afbf846"
If-Modified-Since: Thu, 20 Dec 2012 14:48:28 GMT
3. If not modified, use cached data
If the data have not been updated since your last request, the response status code will be 304 – Not Modified, and no data will be returned.
You can now safely use the cached API response from your previous successful request.
4. If updated, cache the new response
If the rates have changed since your last request, the latest data will returned as usual, along with new ETag
and `Date`` headers.
Repeat Step 1.
Please note: Although ETags help reduce bandwidth for your users, all API requests still count towards your monthly request allowance – even if the data has not changed since your last request.
Further Examples
- This post on the Facebook Developers blog contains a solid run-down of ETags.