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
.
- GET – Retrieves current state of a resource.
- PUT – Creates a new resource.
- DELETE – Deletes a resource.
- 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 Method | URI | Operation |
---|---|---|---|
1 | GET | /JavaCodeGeeks/AuthorService/authors | Get list of all authors |
2 | GET | /JavaCodeGeeks/AuthorService/authors/1 | Get author with id 1 |
3 | PUT | /JavaCodeGeeks/AuthorService/authors/2 | Insert author with id 2 |
4 | POST | /JavaCodeGeeks/AuthorService/authors/2 | Update author with id 2 |
5 | DELETE | /JavaCodeGeeks/AuthorService/authors/1 | Delete author with id 1 |
4. Requirements
For implementing this example, following is the requirement:
- Eclipse for Java EE.
- Apache Tomcat.
- Jersey Library can be downloaded from here.
- Google Chrome with any REST Client extension like Advanced REST client installed.
- 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.
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.
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.
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.
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.
You can download the full source code of this example here: JSONRestWebServiceExample