what is JSON REST interface

Mellon picture Mellon · Mar 29, 2011 · Viewed 23.8k times · Source

Is there any tutorial on JSON RESTful interface (using JAVA servlet) ? The purpose is to call to external REST interface for data, and handle the data by the client(javascript client).

I am not sure what kind of thing is exactly JSON REST interface in JAVA... I need some tutorials to start to learn, so...I ask here.

Answer

joelittlejohn picture joelittlejohn · Mar 29, 2011

JSON is a light-weight data serialization format based on a subset of JavaScript.

A RESTful interface is one that conforms to the constraints and characteristics of the REST architectural style.

So, combining the two, a JSON RESTful interface is one that follows the REST architectural style and uses JSON as its data representation format (typically the content type application/json).

To implement a service of this kind in Java there are frameworks that can help you, such as Jersey or RESTEasy. Both offer additional components that support JSON (for both incoming and outgoing data).

EDIT:

Both Jersey and RESTEasy implement the JAX-RS spec, so it's possible to use either as a 'pure' Java EE way of doing things. If you want to use only the Servlet part of Java EE to do this, it's possible but you'll have to do things like parsing path/template parameters from the URI yourself.

You may find it difficult to use servlet-mapping elements to describe your resource URLs, and this might result in you implementing something that looks very much like JAX-RS (if you end up with one controller servlet that parses the URI and dispatches the request to another object).

I'd suggest reading a lot more on REST before you decide how to implement this. Here's some pointers:

  • Communication between client and server should be stateless. Avoid the HttpSession.
  • REST is resource-centric, not operation-centric (like RPC). Think of the resources that your service exposes and give these URIs.
  • REST resources are manipulated through a common interface. For HTTP services, this interface is defined by the HTTP verbs (GET, POST, PUT, DELETE, etc). Make sure you read section 9 of RFC 2616 to understand the semantics of each verb and the rules around what they should and should not do.
  • Study the response status codes and reason phrases in RFC 2616. These are part of your common interface.
  • RESTful services return representations of resources. A representation has a content type, make sure you set this header so that clients can understand your response.

Finally, if you go the 'pure Servlets' route, you may still find reading/creating JSON a lot easier using a parser library like Jackson.