Monday, August 25, 2014

Hello RESTful Java

Background:
The purpose of the article is to give some background information on, what is RESTful webservices and how this can be possible using Java language. You will understand the following when you finish reading this article.

What you will learn:
  • What is RESTful web services?
  • How to write RESTful web service using Java
Let us first see some of the definitions about RESTful web services.

As per wiki,
REST is an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system and REST stands for Representational state transfer (REST).
So REST is not a technology but it is architectural style for programming. In a highly distributed system, everything can be seen as a resource.
In the background the communication is happening through the plain old HTTP protocol. So REST is completely stateless.

As a programmer we are bored reading lot of contents. So we quickly see some of live coding for writing our first RESTful web services in Java.

The following picture will explain what are the various framework / specification has been used in our demo...

image

Service code:
@Path("/hello")
public class HelloWorldResource {
@GET
@Produces(MediaType.TEXT_PLAIN_TYPE)
public String sayHello() {
return "Welcome RESTful Java";
}
}
Looks so simple know... Now you have written your first REST service in Java. All the annotations are used from Jersey library. So download the Jersey library and put in inside your web application path (WEB-INF/lib).
After you deploy your applicable (rest.war) into any web server, open a browser and hit http://localhost:8080/rest/hello, then you will see "Welcome RESTful Java" in your browser window.
In order to generate JSON string from the given bean object, you can use Gson library.
User user = new User();
user.setId("123");
user.setName("John");
Gson gson = new Gson();
return gson.toJson(user);
The above code will return,
{
"id": "123",
"name": "John"
}
Thanks for reading... Next article we will see how we can set up our environment to start coding with Java and RESTful web services...
All the related source codes are available under https://github.com/LiquidLab/restfullab

No comments:

Post a Comment