How to get correct URL in HTTP header?

Has anyone used the HTTP Accept request header to switch between website and api?

  • We have an ecommerce website that displays groups of products by category using a URL format that maps almost exactly to the REST URL format we would like to use for our forthcoming API. e.g. http://example.com/products/latest or http://example.com/products/hats We also have two search features - the visible search box, which returns results as an HTML page, and the subsequent search refinements (facets) which trigger an AJAX call which returns JSON and updates the HTML in situ. Is it a valid pattern to use the same URL for visible (HTML) and invisible (JSON) results, and to use the Accept http request header to determine what should be returned. i.e. if you call http://example.com/products/latest with Accept: application/json you get just the product data, but if you use text/html you get the full HTML page (header, footer, site chrome etc.) And if so, is this a good idea - will we run into problems if, for instance, the website needs to change, but the API needs to be stable?

  • Answer:

    I guess you could go it like that. one approach would be to do a rewite to the api-service if the client accepts json. However you need to take into consideration what happens if client accepts both.  For a cleaner and easier understood interface I'd recommend returning json if the querystring includes ?format=json. it's easier unerstood by the people using it, and easier to change format. fr instance also offer an xml version for people needing that and offer sorting options etc.

Michael Sørensen at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.