How to use ETags in YouTube API

1.9k views Asked by At

Apparently we can use ETags to see if the channel/playlist has been updated or not based on the following statement from their documentation:

when your application requests a stored resource again, it specifies the ETag associated with that resource. If the resource has changed, the API returns the modified resource and the ETag associated with that version of the resource. If the resource has not changed, the API returns an HTTP 304 response (Not Modified), which indicates that the resource has not changed.

But I tried to get get a channel data which is not changing but after refreshing a couple of times it seems ETag jumps to different values!

1

There are 1 answers

2
jlmcdonald On

You can't just hit the endpoint again and compare etag values; rather, you have to make the request, store the etag value, then pass that etag value in with subsequent requests. You'll do this is the request header ... set the HTTP header "If-None-Match" to the value of your etag. If nothing has changed, you'll get back a 304 (instead of any content or metadata). If something has changed, you'll get a new result, and you take that new etag and store it instead of the old one.

The Google API Client for Javascript supports this header; when you create your gapi.client.request object, you'll pass in an object for arguments; one of the parameters of this object is 'headers,' in which you can set 'If-None-Match' to be equal to the etag you want to check.

(Note, also, that there's an 'If-Match' header, which can also work with etags, where it will only return the content if the resource is the SAME as the one you'd requested previously ... probably not as many use cases for that, but it exists and is supported.)