I am designing a Restful web service for an internal corporate application, and am curious how to merge JSON and “web content” requests.
The web application, like all good corporate applications, has a three-letter abbreviation that is reflected in the URL. Let’s say that this application’s “call sign” is abc, and the users access it at the following URL
When the users access the root of the application we want to serve them up the main html page, the .js files (including jquery), the css, and the images. Then, jquery will start to make AJAX calls back to the server.
What is the best way to handle these multiple content types?
http://servername/abc (returns contents of index.html)
http://servername/abc/javascript/jquery.js (returns a js file)
http://servername/abc/countries/de (returns JSON)
Should I split this into two web contexts? Should I use the jquery contentType parameter in the ajax calls to explicitly specify JSON versus HTML versus something else?
the jQuery
contentTypeis really just a parameter that sets your content-type header on your HTTP request to the server. It is always a best practice to set these for your AJAX calls.Added:
Another good practice is to specifiy the
dataTypeparameter as that will set the accept header on your HTTP request. This is useful for both GET and POST AJAX requests.Most, if not all, web service frameworks (Rails, ASP.NET MVC, .NET WCF, etc..) have abilities to examine the headers of an HTTP request and determine what type of content to serve back
for example:
application/jsonin an HTTP Header would let your webservice know to return a JSON response instead of an HTML or XML response.Some of the better ways that I have seen web apps organized for HTML/JSON serving is to make your standard routes always serve your HTML pages and resources, ie:
http://servername/abc
http://servername/abc/javascript/jquery.js
would do exactly as you have said. For your JSON (or even XML) responses, I see folks create a route that is explicity understood to serve back those types of responses, ie:
http://servername/api/abc/countries/de
the url route begins with an
/api/which would always be understood to serve back a non-html JSON/XML responsethis makes it pretty easy for your company to internally and externally understand that
/api/routes are your JSON/XML responses. It also makes it easier to expose these methods to your customers externally should you want to do that as the infrastructure is there, you would just need to authenticate, etc… the requests.