fbpx
Select Page

RESTful Services in Java

In my previous blog, “What are web-services” (https://www.sevenmentor.com/blog/what-are-web-services, which is the link of my blog), I have explained what is the definition of webservices, what is API and the brief introduction of RESTful Webservices and Soap webservices.

Now, in this blog, I will give the full introduction of Restful webservices.

We will understand the following aspects of these popular services:

  • REST Services and their use of HTTP protocol and HTTP methods
  • Use of particular HTTP method based on the functionality exposed by the service API
  • Guidelines and Best Practices while implementing RESTful Web Services.
  • Examples of RESTful services in Java

So, let’s get started.

 

About REST and its HTTP relation

REST stands for REpresentational State Transfer. REST is a web standards-based architecture and uses HTTP Protocol for data communication.

REST was first introduced by Roy Fielding in year 2000. As a principal author of HTTP specification, which allow for clients and servers interaction over the web, he was involved in ensuring that HTTP remains a very simple protocol in terms of understanding it and using it, but at the same time powerful enough to support complex interactions and usage patterns. This is the reason for the longevity of the HTTP protocol and it remaining there in spite of the huge growth in the web traffic and usage scenarios over the years.

There are a number of design principles, architectural patterns and implementation guidelines that were recommended by him to ensure that interactions based on REST architecture principle work well over the web. These were used in developing REST based or RESTful web services and have gained popularity essentially for their simplicity and because they work really well with existing HTTP based web applications and solutions.

So, each unique URL represents a server-side object in a way. And REST Web Service uses HTTP networking protocol and utilizes the HTTP methods – GET, POST, PUT, DELETE, PATCH – to define what type of operation is done on the object. Creating an object is a POST method, Retrieving the object is GET method, replacing an existing object is PUT method, updating an existing object is PATCH method and deleting the object is represented by DELETE method.

Thus, Rest Web Services are most popular for CRUD services (Create, Retrieve, Update, Delete). The message exchange is mostly using JSON format due to its more lightweight nature, but XML is also an alternative here.

Rest Web Service are more lightweight as they don’t require heavy parsers and protocol implementations. One of its primary reason is that they run directly over the HTTP protocol. Also, they are more readable and easier to build. This is one of the reasons why they have become popular in Web2.0 applications.

But the trade-off of messaging standards and standards to address other aspects like transactions and addressing limits some complex scenarios where these are a need.

For example, use of HTTP directly and not having addressing standard leads to point-to-point client server interactions. Though in this case, we have additional solutions like API Gateways that could allow to break these interaction patterns.

Nevertheless, Rest Web Services are still very popular as CRUD scenarios are what applications usually expose to outside world.

RESTful Services in Java image 1

Service Operations and HTTP Methods mapping

 

Service Operation HTTP Method Description
Retrieve/Read GET Show information about the resource – the resource can be a single value or a collection
Create POST Create the resource, persist the record passed as input in the request
Update/Modify PUT Update or modify an existing resource with the details passed as input in the request. In case the resource does not exist already, then create a new record/resource. Its equivalent to an upsert operation.
Destroy/Delete DELETE Remove or delete the resource or record.
Partial Update PATCH Not used much due to complexity in implementation. Make a partial change to an existing resource. The changes to be made are passed as a PATCH document.

 

RESTFul Applications

For explaining RESTful webservices, I am sharing two programs. The first program is without database so that you can understand how to make webservices in java.

The second program is with a database so that we can explain each method of Http.

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

RESTFul Service without Database

I am creating program using spring mvc webservices. Here are the steps:

Step 1

Create a Dynamic webproject  TestMvcWebService and add required jar file in the project.

Step2

Create a bean class Employee.

package com.restexample;

public class Employee {

            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;

            }

}

 

Step3

Create a RestController class i.e. TestRestMessageController

package com.restexample;

 import java.util.ArrayList;

import java.util.List;

 import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 @RestController

public class SpringRestMessageController {

           

@RequestMapping(value=”/emps/{id}”,method=RequestMethod.GET)

           

            public Employee getEmployee(@PathVariable(“id”) int empId) {

                        Employee emp=new Employee();

                        emp.setId(empId);

                        emp.setName(“test”);

                        return emp;

            }

           

            @RequestMapping(value=”/emps” ,method=RequestMethod.GET)

           

            public List<Employee> getEmployee(){

                       

                        List<Employee> list=new ArrayList<Employee>();

                       

                        Employee emp=new Employee();

                       

                        emp.setId(999);

                        emp.setName(“test999”);

                        list.add(emp);

                        return list;

            }

             @RequestMapping(value=”/emp” ,method=RequestMethod.POST)

                       public Employee addEmployee(@RequestBody Employee newEmp){

                                               Employee emp=new Employee();

                                               emp.setId(888);

                        emp.setName(newEmp.getName());

                        return emp;

            }

 

}

 

The annotations used here are discussed in details later on in the blog.

Step 3

Create a web.xml file

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd” id=”WebApp_ID” version=”3.1″>

  <display-name>TestMvcWebService</display-name> 

   <servlet>

  <servlet-name>dispatcher</servlet-name>

  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  <init-param>

  <param-name>contextConfigLocation</param-name>

  <param-value>WEB-INF/restServiceContext.xml</param-value>

  </init-param> 

  <load-on-startup>1</load-on-startup> 

  </servlet>

  <servlet-mapping>

  <servlet-name>dispatcher</servlet-name>

  <url-pattern>/</url-pattern>

  </servlet-mapping>

  <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>

</web-app>

Step 4

Create restServiceContext.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans”

            xmlns:mvc=”http://www.springframework.org/schema/mvc”

            xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

            xmlns:context=”http://www.springframework.org/schema/context”

             xsi:schemaLocation=”http://www.springframework.org/schema/beans

             http://www.springframework.org/schema/beans/spring-beans.xsd

              http://www.springframework.org/schema/context

              http://www.springframework.org/schema/context/spring-context.xsd

              http://www.springframework.org/schema/mvc

              http://www.springframework.org/schema/mvc/spring-mvc.xsd”>             

              <mvc:annotation-driven></mvc:annotation-driven>

              <context:component-scan base-package=”com.restexample”></context:component-scan>             

</beans>

Invoke the REST Web Service

Use Restlet Client or Postman to invoke the REST Web Service.

RESTful Services in Java image 2

RESTful Service with Database

This program would utilize a database to explain the other REST Service methods and operations – especially update and delete operations.

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

Step 1

First create a project ClientWebServices and add the jar in the file.

Step 2

Create a model class

package com.rest; 

public class Client { 

            private int clientid; 

            private String clientname; 

            private String clientcity; 

            private String clientservices;                      

            public int getClientid() {

                        return clientid;

            }

            public void setClientid(int clientid) {

                        this.clientid = clientid;

            }

            public String getClientname() {

                        return clientname;

            }

            public void setClientname(String clientname) {

                        this.clientname = clientname;

            }

            public String getClientcity() {

                        return clientcity;

            }

            public void setClientcity(String clientcity) {

                        this.clientcity = clientcity;

            }

            public String getClientservices() {

                        return clientservices;

            }

            public void setClientservices(String clientservices) {

                        this.clientservices = clientservices;

            } 

   }

Step 3

Create ClientDao class for database:

 

package com.rest;

 

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List; 

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper; 

public class ClientDao { 

            JdbcTemplate template;              

            public void setTemplate(JdbcTemplate template) { 

                this.template = template; 

            } 

              public Client getClientById(int id){ 

                String sql=”select * from clienttable where clientid=?”; 

                return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Client>(Client.class)); 

            } 

            public List<Client> getAllClients(){ 

                return template.query(“select * from clienttable”,new RowMapper<Client>(){ 

                    public Client mapRow(ResultSet rs, int row) throws SQLException { 

                        Client c=new Client(); 

                        c.setClientid(rs.getInt(1));  

                        c.setClientname(rs.getString(2)); 

                        c.setClientcity(rs.getString(3)); 

                        c.setClientservices(rs.getString(4)); 

                        return c; 

                    } 

                }); 

            } 

            public int insertClient(Client c) {                    

                        String query=”insert into clienttable(clientid,clientname,clientcity,clientservices) values(?,?,?,?)”;

                        return template.update(query,c.getClientid(),c.getClientname(),c.getClientcity(),c.getClientservices());

                        }

            public int updateClient(Client c) {                  

                        String query=”update clienttable set clientname=?,clientcity=?,clientservices=? where clientid=?”;

                        return template.update(query,c.getClientname(),c.getClientcity(),c.getClientservices(),c.getClientid());

                        }

 

            public int deleteClient(int id) {

                       

                        String query=”delete from clienttable where clientid=?”;

                        return template.update(query,id);

            }

}

Step 4

Create RestController class

package com.rest; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController; 

@RestController

public class ClientController { 

            @Autowired 

   ClientDao dao;

           

              @RequestMapping(value=”/clients”,method=RequestMethod.GET) 

                public List<Client> viewclients(){ 

                    List<Client> list=dao.getAllClients(); 

                    return list; 

                }             

              @RequestMapping(value=”/clients/{id}”,method=RequestMethod.GET) 

                public Client viewclient(@PathVariable int id){ 

                    Client client=dao.getClientById(id); 

                    return client; 

                }

              @RequestMapping(value=”/clients”,method=RequestMethod.POST) 

                public int saveclient(@RequestBody Client c){ 

                    return dao.insertClient(c);

                }

              @RequestMapping(value=”/clients”,method=RequestMethod.PUT) 

                public int updateclient(@RequestBody Client c){ 

                    return dao.updateClient(c);

                }

              @RequestMapping(value=”/clients/{id}”,method=RequestMethod.DELETE) 

                public int deleteclient(@PathVariable int id){ 

                    return dao.deleteClient(id); 

                }

}

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

Step 5

Create a spring-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?> 

<beans xmlns=”http://www.springframework.org/schema/beans”   

    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”   

    xmlns:p=”http://www.springframework.org/schema/p”   

    xmlns:context=”http://www.springframework.org/schema/context”

    xmlns:mvc=”http://www.springframework.org/schema/mvc”  

    xsi:schemaLocation=”http://www.springframework.org/schema/beans   

            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   

            http://www.springframework.org/schema/context   

            http://www.springframework.org/schema/context/spring-context-3.0.xsd

            http://www.springframework.org/schema/mvc

            http://www.springframework.org/schema/mvc/spring-mvc.xsd”>    

  <mvc:annotation-driven></mvc:annotation-driven> 

<context:component-scan base-package=”com.rest”></context:component-scan> 

<bean id=”ds” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”> 

<property name=”driverClassName” value=”com.mysql.jdbc.Driver”></property> 

<property name=”url” value=”jdbc:mysql://localhost/mydatabase”></property> 

<property name=”username” value=”root”></property> 

<property name=”password” value=”root”></property> 

</bean>  

<bean id=”jt” class=”org.springframework.jdbc.core.JdbcTemplate”> 

<property name=”dataSource” ref=”ds”></property> 

</bean>  

<bean id=”dao” class=”com.rest.ClientDao”> 

<property name=”template” ref=”jt”></property> 

</bean> 

</beans> 

 

Step 6

create a web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://xmlns.jcp.org/xml/ns/javaee” xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd” id=”WebApp_ID” version=”3.1″>

  <display-name>CleintWebServices</display-name> 

   <servlet> 

    <servlet-name>spring</servlet-name> 

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 

    <load-on-startup>1</load-on-startup> 

</servlet> 

<servlet-mapping> 

    <servlet-name>spring</servlet-name> 

    <url-pattern>/</url-pattern> 

</servlet-mapping> 

  <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>

</web-app>

Note: You can find the attached jar file in my BLOG. So you can download from there.

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

Invoking the Service

Use Restlet Client or Postman tool to invoke the RESTful Web Service that was created above.

RESTful Services in Java image 3

Spring Annotations Explained

There are a few spring annotations used in the application code snippets above. These are explained in brief below. Its recommended to refer to the Spring documentation for a detained explanation for the same.

Annotation Description Example
@RestController @RestController is used to create RESTful web services in Spring MVC framework.

This annotation is added to the class to indicate that it is a request handler.

Spring RestController maps the input request data to the correct request handler method of the class. Also, it converts the response of the handler to the corresponding JSON/XML response.

To understand the request message structure, the HTTP content-type header is used (application/xml or application/json).

Also, to understand what response structure is acceptable to the client, so that the response conversion is correct, the HTTP Accepts header is used (application/xml or application/json).

RestController ensures that it sends the proper content-type header in the response to indicate the response structure it converted the object to.

@RestController

public class ClientController {

}

@RequestMapping @RequestMapping specifies the base URL that maps to the method it is annotating. Also used to specify the HTTP Request Method that maps to the handler method.   @RequestMapping(value=”/clients”,method=RequestMethod.GET)

public List<Client> viewclients(){

}

 

So, the “/clients” HTTP GET request maps to the viewclients method.

@RequestBody @RequestBody informs Spring that the input http request body needs to be mapped to the parameter it is annotating. Spring then uses message convertors (marshal/unmarshal) to convert the HTTP message body to the corresponding object.

To understand the input message structure, the request’s content-type (application/xml or application/json)

@RequestMapping(value=”/clients”,method=RequestMethod.POST)

public int saveclient(@RequestBody Client c){

return dao.insertClient(c);

}

 

Map the POST request body to the Client object of the saveclient function.

@PathVariable @PathVariable informs Spring what segment of the URL path should be mapped to the handler’s method argument.   @RequestMapping(value=”/clients/{id}”,method=RequestMethod.GET)

public Client viewclient(@PathVariable(“id”) int id){

 

From the URL /clients/{id}, map the “id” path segment to the id argument of the viewclient function.

So, if the request URL sent by the client is /clients/101, then 101 is assigned to id argument – viewclients (101).

 

 

Influencing Request and Response structure

Our REST applications can handle and work with both XML and JSON request and same is the case with the responses. So how does it know whether the request is XML or JSON. Also how does it know whether to return an XML or JSON response and what is acceptable to the client invoking the RESTful web service.

This behaviour is controlled by two HTTP headers – content-type and Accepts.

Content-type

As highlighted above, changing the content-type HTTP header in the request, defines what is the type of the content in the HTTP body.

If the content-type is “application/xml”, then Spring treats the HTTP body as XML and uses the XML message convertor to convert it to a Java object.

If the content-type is “application/json”, then Spring treats the HTTP body as JSON and uses the JSON message convertor to convert it to a Java object.

Accepts

Passing in the Accepts HTTP header in the request allows Spring to understand what response message structure is acceptable to the client of the RESTful service.

 

If the Accepts header is “application/xml”, then Spring uses the XML message convertor to convert the response object of the handler function to a XML message.

If the content-type is “application/json”, then Spring uses the JSON message convertor to convert the response object of the handler function to a JSON message.

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

To check this behaviour, set the headers in the message using the Test Client (Restlet Client or Postman). An example in Restlet client is shown below:

RESTful Services in Java image 4

REST URL Naming Conventions

The idea of REST architectural principles is to keep service implementations simple. This is highlighted in the use of HTTP methods and mapping them to the service operations. The same applies to REST URL names for the operations.

Though the URL names are something that application developers can decide as they want, to keep things simple there are certain conventions and recommendations that can be followed. These are conventions that a lot of the service APIs follow across applications. It makes it easier for users of the APIs to understand them and also for the developers to maintain and enhance the applications.

Since RESTful services are targeting CRUD operations on a resource, depending on the resource in question the URLs would be created.

Single Resource/Resource Collection

The resource can be a single resource like a single client or a collection like all the clients (consider the application example above).

 

Service Operation URL HTTP Method Description
Retrieve/Read /clients

/clients/{id}

GET Show information about the resource – the resource can be a single value or a collection
Create /clients POST Create the resource, persist the record passed as input in the request
Update/Modify /clients/{id} PUT Update or modify an existing resource with the details passed as input in the request. In case the resource does not exist already, then create a new record/resource. Its equivalent to an insert+update (upsert) operation.
Destroy/Delete /clients/{id} DELETE Remove or delete the resource or record.

 

In Conclusion

I hope this blog would have helped you understand RESTFul Web Services and cleared some of the basic concepts around it. Also, the examples helped you realize how to create your RESTful Web Services using Java and Spring. So, go ahead and create your own services – there’s nothing like trying things yourself.

Looking forward to your experiences and comments here.

Note: you can Download the Supportive Library Files to Run Above Program! download-image

kirru

Author: Kiran Tiwari

Designation: Software Trainer

Company:  Seven Mentor Pvt. Ltd.

Call the Trainer and Book your free demo Class for JAVA now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

 






Pin It on Pinterest