Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the output format encoded in a RESTful URL?

Tags:

rest

html

http

url

Assume I have a RESTful web service, which holds information about an object that can be accessed at an url like http://example.com/myobject. I would like to be able to retrieve this information in two formats: firstly, the XML-formatted plain data, and secondly, as a full HTML page, which may also include a javascript interface to change the object and PUT it back with AJAX.

What is the canonical way to achieve this? Should I publish my object at two different urls like http://example.com/myobject?format=xml and ...format=html? (Are there better ways than using a query string to distinguish the URLS here?) Or is it sensible to send something like multipart MIME data and can I rely on browsers being able to extract the HTML part? Or is there some HTTP header field in the request I could use?

(With PUT or POST requests sent in different formats, it is much easier as the server can check the format and parse it accordingly.)

like image 555
Marc Avatar asked Feb 24 '23 22:02

Marc


2 Answers

You could alternatively use content negotiation instead of querystring parameters. In a nutshell, the client sends the acceptable media types via the Accept header in the request (e.g. "application/xml, text/html;q=0.9"), and the server analyzes this and replies with the client-preferred media type (this process is called server-driven negotiation)

When doing server-driven negotiation, the response should contain a Vary header indicating what request header was used in the negotiation

Keep in mind that for this to work the client must send an appropriate Accept header.

like image 146
Mauricio Scheffer Avatar answered Feb 26 '23 20:02

Mauricio Scheffer


A way which happens to be very easily readable, is to just use the extension:

http://example.com/myobject.html
http://example.com/myobject.xml
http://example.com/myobject.json
etc.

Otherwise you could use the request's accepted content type, which you can find in the request header, e.g. text/html for HTML, text/xml for XML, text/json for JSON, and so on. This is called Content Negotiation:

Content negotiation is a mechanism defined in the HTTP specification that makes it possible to serve different versions of a document (or more generally, a resource) at the same URI, so that user agents can specify which version fit their capabilities the best.

That would leave your URLs very simple and you would deliver HTML output when nothing else is specified (and the page is accessed through the browser).

like image 23
slhck Avatar answered Feb 26 '23 21:02

slhck