Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest Content Negotiation and Caching

I'm wondering how caching works with content negotiation based API. Since the to get a resource in XML or JSON, the URI will be the same, for example:

http://example.com/bikes/mountain

The service returns JSON / XML based on the Accept type header. How smart are caches?

For example:

  • if one client requested this using Accept type to return XML.
  • the response is cached by web server for say 1 minute.
  • second client requests same resource using Accept type to return JSON

Does caching check accept / content types at all? Or would this result in the JSON requester getting XML data back since thats what the server had cached? I'm hoping this is something so obvious its already been taken care of, otherwise, isn't that a pretty large argument to include .xml / .json in the URI?

I guess my question is basically, can i safely use content negotiation while still using standard caching techniques?

like image 478
Rosstified Avatar asked Jun 10 '10 13:06

Rosstified


2 Answers

Darrel is correct in that the Vary header tells the client which request headers it can vary to get different representations of a resource.

That value tells the client that it can ask for the representation in a different file format, by setting or changing the Accept header (in your case, JSON or XML). You could also get a different representation of your mountain bike in English and in French if you use the Accept-Language header.

The two requests send different values, so they should always be cached separately.

When you use a value of '*' in Vary header, that means the response should not be cached.

like image 75
randombits Avatar answered Nov 02 '22 06:11

randombits


Yes. Look at the description of the Vary header in RFC 2616

In my simplistic understanding of the vary header, caches will use the header fields that are named in the vary header to uniquely identify the cached representation.

like image 36
Darrel Miller Avatar answered Nov 02 '22 06:11

Darrel Miller