rest

Java JSON RESTful Web Service Example

In this example we shall learn implementing Restful Web Service in Java where the data interchange format shall be JSON.

1. Introduction to RESTful Web Services

RESTful Web Services follow REST architecture which stands for REpresentational State Transfer. RESTful web services are light weight and highly scalable is one of the most common way to create APIs on web.

In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs). REST uses various representations to represent a resource like text, JSON and XML.

2. HTTP Methods

In REST, resources are manipulated using a fixed set of four HTTP create, read, update, delete operations: PUT, GET, POST, and DELETE.

  1. GET – Retrieves current state of a resource.
  2. PUT – Creates a new resource.
  3. DELETE – Deletes a resource.
  4. POST – Updates an existing resource or creates a new resource if it doesn’t exist.

3. HTTP Methods

Following is the sample usage of HTTP methods with RESTful Web Service. We shall be implementing the GET HTTP method in our example where data interchange format shall be JSON.

S.No.HTTP MethodURIOperation
1GET/JavaCodeGeeks/AuthorService/authorsGet list of all authors
2GET/JavaCodeGeeks/AuthorService/authors/1Get author with id 1
3PUT/JavaCodeGeeks/AuthorService/authors/2Insert author with id 2
4POST/JavaCodeGeeks/AuthorService/authors/2Update author with id 2
5DELETE/JavaCodeGeeks/AuthorService/authors/1Delete author with id 1

4. Requirements

For implementing this example, following is the requirement:

  1. Eclipse for Java EE.
  2. Apache Tomcat.
  3. Jersey Library can be downloaded from here.
  4. Google Chrome with any REST Client extension like Advanced REST client installed.
  5. Genson library for JSON conversion can be downloaded from here.

5. Project Setup

To start with the project setup, first create Dynamic Web Project in Eclipse.

Create Dynamic Web Project
Create Dynamic Web Project

Configure a web server like Apache Tomcat in your Eclipse environment. In my case, I had already configured the server, for which I also got an option against Target Runtime to choose while creating new Dynamic Web Project as shown above.

Now copy all libraries downloaded form Jersey‘s and Genson‘s website to WEB-INF/lib folder.

Copy Jersey and Genson Libraries
Copy Jersey and Genson Libraries

With all this, project setup is complete and now we shall learn implementing RESTful Web Services.

6. Implementing RESTful Web Service

First we shall configure Jersey to serve as servlet dispatcher for servlet requests. To do this we shall modify web.xml as follows.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>JavaJsonRestWebServiceExample</servlet-name>
		<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
		<init-param>
			<param-name>jersey.config.server.provider.packages</param-name>
			<param-value>com.javacodegeeks.examples.jersey, com.jersey.jaxb, com.fasterxml.jackson.jaxrs.json</param-value>
		</init-param>
		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>JavaJsonRestWebServiceExample</servlet-name>
		<url-pattern>/JavaCodeGeeks/*</url-pattern>
	</servlet-mapping>
</web-app>

In web.xml, notice the configuration of ServletContainer and how packages folder has been configured that shall be searched for web service implementation.

Next we shall implement a POJO class whose object we shall return as a JSON via REST GET api.

Person.java

package com.javacodegeeks.examples.jersey;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public Person() {
		super();
	}
}

Now comes the last step in implementing web service.

AuthorService.java

package com.javacodegeeks.examples.jersey;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/AuthorService")
public class AuthorService {
	@GET
	@Path("/authors")
	@Produces(MediaType.APPLICATION_JSON)
	public List getTrackInJSON() {
		List listPerson = new ArrayList();
		Person p1 = new Person();
		p1.setId(1);;
		p1.setName("name1");
		Person p2 = new Person();
		p2.setId(2);
		p2.setName("name2");
		listPerson.add(p1);
		listPerson.add(p2);
		return listPerson;
	}
	
	
}

Notice the line of code @Produces(MediaType.APPLICATION_JSON) above. With this we are telling the web service that response shall be of type JSON.

Now that implementation of REST Web Service with GET HTTP Method is complete, we shall start the Tomcat server which we configured in Target Runtime above.

7. Testing RESTful Web Service

Now that implementation of web service is complete, we shall be testing the same now.

To test the web service open Google Chrome, open Developer Tools, and go to Network tab.

Chrome Developer Tools
Chrome Developer Tools

Now enter following URL in Address Bar and press Enter:

http://localhost:8080/JSONRestWebServiceExample/JavaCodeGeeks/AuthorService/authors

Notice that in Developer Tools Network tab, a new request will appear. Click on it and then click on Response tab within.

REST Response
REST Response

Here we can see a JSON response as returned from web service.

8. Download the Source Code

This was an example of Java JSON RESTful Web Service.

Download
You can download the full source code of this example here: JSONRestWebServiceExample

Saurabh Arora

Saurabh graduated with an engineering degree in Information Technology from YMCA Institute of Engineering, India. He is SCJP, OCWCD certified and currently working as Technical Lead with one of the biggest service based firms and is involved in projects extensively using Java and JEE technologies. He has worked in E-Commerce, Banking and Telecom domain.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button