RESTful – Quick Guide For Beginners

If you desire to build an application program interface (API) for web applications, RESTful is used. What is an application program interface (API)? An Application Program Interface is a mediator between any two software applications. It enables two software applications to communicate with each other safely and securely. Typical API applications in daily life are using Facebook, using chatting applications, or using a weather forecasting app on the mobile phone. 

Let us observe one straightforward example to understand what exactly an API is? Consider the example of a restaurant. We go to a restaurant and eat the food of our choice. What we do is we observe the menu card and tell the waiter about your selected items from the menu. The waiter then informs your order to the kitchen department, and your food gets prepared. After food is ready, the waiter serves it at your table for you. Here, the waiter is the interface between you and the kitchen department. The same happens while two systems communicate.

An application program interface (API) is categorized into four primary types, OpenAPIs, Partner APIs, Internal APIs, and Composite APIs. OepnAPIs are allowed to be accessed by everyone, as they are available publicly. In Partner APIs, a particular user needs the appropriate right to access it, as they are not developed for public use. Internal APIs are specially designed for the company’s internal use. Lastly, composite APIs are generally used for speeding up the company’s operations and performance. 

Another API type is web service APIs. There are four primary web service APIs, SOAP, XML-RPC, JSON-RPC, and REST. SOAP implies a Simple Object Access Protocol, which transfers data using the XML format. The SOAP API involves the use of Web Services Definition Language (WSDL) for defining its interface. Another web service API is XML-RPC. As its name suggests, it used the XML form for data sharing. The XML-RPC API is simpler and more accessible than the SOAP API. 

The next web service API is JSON-RPC. It is the same API as the XML, but it uses JSON format for data sharing. Lastly, the REST API is different from all the above three. It is the collection of architectural standards. The REST API is also called RESTful API. It is one of the commonly used web service APIs, as it requires exceptionally less bandwidth. 

In this article, we will see a quick guide about the RESTful web service. This post will help you to learn all about the RESTful web service. We have explained the RESTful web service concepts more straightforwardly with easy examples. One thing to remember before starting to understand the RESTful API is you must possess a better knowledge of Java programming language, HTML, CSS, AJAX, and Text Editor, as RESTful is a web service for developing web applications. So, let us start our RESTful API tutorial. 

What is RESTful Web Service API?

Before we know what the RESTful API is, we shall know first what the web service actually is. A web service is a set of standards or principles required for sharing or exchanging data between systems. Today, we use multiple applications on our mobile phones and desktops. These applications are written in numerous programming languages, and still, they work on distinct operating systems. A web service enables you to access a particular software application on different operating systems.  

The RESTful API is a web service API. It includes a collection of architectural standards and utilizes an HTTP protocol for accessing and using particular data. REST implies Representational State Transfer. In the RESTful API, every component involved is treated as a resource. You can access these resources using the HTTP protocol methods. 

There is a server and a client involved in the RESTful API. The REST API’s clients can access the resources provided by the server and manipulate them. Each resource has a separate URI or global ID. Using the URI or global ID, we can identify the resources in the RESTful API. URI implies a Uniform Resource Identifier. You can use text, XML.JSON, or JSON formats in the REST API for the resource representation. 

The RESTful web service is typically used by cloud consumers, enabling them to access and manage web services. The REST API serves as one of the most desirable choices for creating a robust API. An API built using the REST architecture permits users to interact with cloud services manageably. Some of the popular websites that use the RESTful web service for making their APIs are Amazon Web Services (AWS), Twitter, LinkedIn, and Google. 

Working of the RESTful Web Service API

We have observed a brief description of the RESTful web service. Now, let us know the working of the RESTful API. The RESTful API breaks down every single transaction between any two applications into multiple smaller modules. Here, the transaction implies the exchange of data or information. Each module holds the essential information of the transaction. Hence, developers feel comfortable and flexible in building an API for any web application. 

Today, many companies, like Cloud Data Management Interface (CDMI), AmazonS3, etc., offer their particular models for developing an API. There are numerous commands in the RESTful API web service for accessing resources. The resource representation defines a specific resource’s state at a given timestamp. 

HTTP Methods in RESTful web service API

The RESTful web service API uses the HTTP protocol for accessing and manipulating resources. There are four primary HTTP methods used in the RESTful web service, GET, PUT, POST, DELETE. Let us briefly know each of these HTTP methods. 

  1. GET: The GET method enables users to access RESTful API’s resources. But, they cannot be changed or manipulated. Using the GET method, you can only read resources. 
  2. PUT: The HTTP PUT method allows you to modify the resources or change their states. It also permits you to create another new resource.
  3. POST: You can use the POST method for creating a new resource.
  4. DELETE: The HTTP DELETE method is used for deleting the resource. 

The RESTful web service API supports several data formats, like application/xml, application/json, application/x-www-form-urlencoded, application.x-web+xml, and multipart/form-data. 

RESTful API Architecture Properties and Constraints

Dr. Roy Fielding is the developer of the RESTful web service API. Below are some significant properties and constraints of the RESTful API architecture. 

Properties of the RESTful API

  1. The RESTful API offers high performance to the end-users. When a user clicks on any link, he or she is being provided with instant results. And the developers deliver all services to users. 
  2. Another property of the RESTful API is scalability. The RESTful API provides services regularly despite the users increase or decrease. 
  3. The RESTful API has a uniform interface. All the resources are identified using their respective URIs. Hence, this uniform interface makes the RESTful API simple. 
  4.  The next property is modifiability. Any change in the system should take place with ease and comfort. 
  5. RESTful API architecture is highly portable and reliable. 

Architectural Constraints of the RESTful API

For any RESTful web service API, the below six architectural conditions must hold. 

  1. The first architectural constraint for the RESTful web service API is it should use a uniform interface. All the RESTful API resources should be identified using their respective Uniform Resource Identifiers (URIs). They must be accessed and manipulated only through the four HTTP methods, PUT, POST, GET, and DELETE. 
  2. The client and the server in the RESTful API should have a precise representation. The client handles the uniform interface and request gathering. On the other hand, server regulates security, data access, and workload management. The server holds all the resources, and the client requests resources from the server. 
  3. Another architectural constraint for the RESTful web service API is stateless operations. The client and the server in the RESTful API should follow stateless functions. All state management operations should be carried out on the client-side. 
  4. All the RESTful web service API’s should perform caching. If it is represented that the caching is not possible, then only the caching should not be performed. 
  5. The architecture of a particular application should contain the server on multiple layers. A single layer should not have any information regarding other layers, except its immediate layer. 
  6. Generally, the server sends the resources’ static representations to the client in the XML or JSON format. It should also transmit the executable code to the client when required. 

In the further segment, we will learn how to generate a web service using the HTTP methods. We will use two HTTP methods, GET and POST, for creating user management. The following are some essential functionalities used:

  1. Using the HTTP GET method with an empty POST body, we will display a list containing user names. Take a Uniform Resource Identifier as /User/Service/users
  2. Later, we will add the details of every user into a list. For this purpose, we will use the HTTP POST method, with JSON String in the POST body. Use the URI as /User/Service/addUser
  3. Lastly, we will display the details of separate users using the HTTP GET method. Keep the POST body empty and use the URI as /User/Service/getUser/:id

Environment Set-up for RESTful Web Services

For working with the RESTful web service, we will use the Jersey Framework. This framework implements the standard specification, called JAX-RS 2.0 API. Using this specification, we can generate RESTful web services. Before we move towards the Jersey Framework, we shall learn to set up the Eclipse, Tomcat, and JDK environment on your computer system. We have explained setting up all three environments on the system with accurate and straightforward steps.

How to set-up the Java Development Kit (JDK)?

The Java Development Kit (JDK) is one of the essential packages used for running Java code. The JDK package in Java enables users to write the Java programs. You have to download this package, named JavaSE, from this website:

After downloading, install it with the help of the guidelines provided. Once done, you have to fix the PATH and JAVA_HOME environment variables to the place where ‘java’ and ‘javac’ are present. Generally, ‘java’ is present in java_install_dir/bin, and ‘javac’ is present in ‘java_install_dir.’

For fixing the PATH and JAVA_HOME environment variables on the Windows XP, NT, or 2000 systems, go to ‘My Computer, right-click on it, and click on ‘Properties.’ You will notice the ‘Advanced tab.’ Click on it and later click on ‘Environment Variables.’ Change the PATH and JAVA_HOME environment variables with the ‘java’ and ‘javac’ location on the system, and click on the ‘OK’ button. Your environment variable set-up is done.

For Linux and Solaris systems, follow the below steps. Consider you use a C shell, and you have downloaded the JavaSE file in the /usr/local/jdk1.7.9_75 location. Update the ‘.cshrc’ file with the below commands:

setenv PATH /usr/local/jdk1.7.0_75/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.7.0_75

How to set-up Eclipse IDE?

The first thing you have to follow is to download the latest binaries of Eclipse from its official website.

After downloading the newest Eclipse binaries, place them at a proper location on your system. Consider we have located the Eclipse binaries on the Windows systems in C:\eclipse. We will locate the Eclipse binaries at /usr/local/eclipse location for the Linux or Unix system. After you place it at the proper location, fix the PATH variable to the place where you have kept the Eclipse binaries. 

For starting Eclipse, double click on the eclipse.exe file, or you can type the below command on the Windows command prompt.

%C:\eclipse\eclipse.exe

If you use Eclipse on the Linux or Solaris system, use the below command for starting it.

$/usr/local/eclipse/eclipse

If everything goes well and the set-up is proper, the application starts, and the screen appears for writing the code.  

How to set-up Apache Tomcat?

Here, we will understand how to install and set-up your system’s environment for Apache Tomcat. Firstly, you have to download the latest Tomcat version on this website.

After downloading this latest Tomcat version, place it at a suitable location on your system. 

Let us consider we placed the Tomcat Apache file on the Windows system at the C:\apache-tomcat-7.0.59 location. We will place the Tomcat Apache file at /usr/local/apache-tomcat-7.0.59 location on the Linux or Solaris system. After that, you have to fix the CATALINA_HOME environment variable to the place where you have kept the downloaded Tomcat Apache file. 

You can start the Tomcat application on your Windows system by clicking the startup.bat file. You can also use the following command for starting the Tomcat application.

%CATALINA_HOME%\bin\startup.bat

or 

C:\apache-tomcat-7.0.59\bin\startup.bat

If you are using the Tomcat application on the Linux or Solaris system, you have to follow any one of the below commands for starting it. 

$CATALINA_HOME/bin/startup.sh

or 

/usr/local/apache-tomcat-7.0.59/bin/startup.sh

When everything is fine, a screen appears where you can write the code and run it. All default applications with Tomcat will be available by visiting the below website:

The complete information about Tomcat configuration and running programs on it is available on the website

If you wish to stop the Tomcat application on the Windows system, type any one of the following commands. 

%CATALINA_HOME%\bin\shutdown

or 

C:\apache-tomcat-7.0.59\bin\shutdown

You can type any one of the two commands mentioned below for shutting down the Tomcat application.

$CATALINA_HOME/bin/shutdown.sh

or 

/usr/local/apache-tomcat-7.0.59/bin/shutdown.sh

How to set-up Jersey Framework Libraries?

After setting up the JDK, Eclipse, and Tomcat Apache, you can now go for setting up the Jersey Framework. Follow the below guidelines sequentially to download the Jersey Framework. 

  1. Firstly, you have to decide on the operating system, like Windows or Unix, to install the Jersey Framework on it. If you choose the Windows system, download the .zip file, and for the Unix systems, download the .tz file. 
  2. The next step is to download the newest Jersey Framework binaries from the below website.
  3. After downloading the .zip file on the Windows system, you need to unzip it. Suppose you have downloaded the jaxrs-ri-2.17.zip file. After unzipping this file, it provides a directory structure at the E:\jaxrs-ri-2.17\jaxrs-ri location. 
  4. All the Jersey libraries will be in the C:\jaxrs-ri-2.17\jaxrs-ri\lib directory, and dependencies will be present at C:\jaxrs-ri-2.17\jaxrs-ri\ext. 
  5. Later, fix the CLASSPATH variable to the place where your Jersey libraries are present, C:\jaxrs-ri-2.17\jaxrs-ri\lib directory. Remember that there is no need to fix the CLASSPATH variable for the Jersey Framework if you use the Eclipse application. 

You now know how to set-up the environment for the RESTful web service. Follow all the above steps, and you will be ready to write the Jersey example. 

RESTful First Example – Jersey (JAX-RS)

After setting up the Java, Tomcat Apache, Eclipse, and the Jersey Framework environment, you can start building web applications using the RESTful API. Let us observe one example in the Jersey Framework to get a precise idea about writing the program in RESTful API. You have to follow the below steps mentioned sequentially to run the program successfully.

Step 1: Create a Java Project

Create a Java project using an Eclipse IDE. Here, we will create a Dynamic Web Project. Below are the steps to develop the Dynamic Web Project in an Eclipse IDE. 

  1. Start the Eclipse application from your system. Click on the File option, click on New, and select the New Project. 
  2. Later, choose the wizard Dynamic Web Project from the wizard list. 
  3. After selecting the wizard, give the desired name to your project, say FirstRestExample.
  4. When you save your project name in the wizard window, go to the Project Explorer, and you will notice your project name there. 

Step 2: Add the Necessary Libraries

After creating the project and saving it with a specific name, you have to add the Jersey Framewoek’s libraries and dependencies to your project. We have listed the jar file names to be copied in the WEB-INF/lib directory of the created project from the jersey’s zip folder. 

  • \jaxrs-ri-2.17\jaxrs-ri\api
  • \jaxrs-ri-2.17\jaxrs-ri\ext
  • \jaxrs-ri-2.17\jaxrs-ri\lib

For adding the above jar files mentioned to your project, right-click on your project, FirstRestExample. Click on the Build Path option and then go to the Configure Build Path. Here, you will see the window displaying the Java Build Path. Additionally, you will see the Add JARs button under the Libraries menu. Add the jar files in the WEB-INF/lib directory. 

Step 3: Create the source files

We have created our project, named FirstRestExample, in the Eclipse IDE. Now, we have to create the source files for this project. For making the source files, we first require to create a package, say com.restexample. Go to the package explorer and right-click on the src option. You will find the New option. Click on it and later click on the Package option. 

Here you need to create three different files under the com.restexample package. Let us name the files as EmployeeService.java, Employee.java,  and EmployeeDao.java. In the three files, you created under the com.restexmaple package, and you need to write the code. We will first write the code in the Employee.java file. 

Employee.java

package com.restexmaple; 
import java.io.Serializable; 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employee")
public class Employee implements Serializable { 
  private static final long serialVersionUID = 1L;
  private int empId;
  private String empName;
  private String empPosition; 
  public Employee(){}
      public Employee(int empId, String empName, String empPosition){ 
      this.empId = empId;
      this.empName = empName;
      this.empPosition = empPosition;
  } 
  public int getEmpId() {
      return empId;
  } 
  @XmlElement
  public void setEmpId(int empId) {
      this.empId = empId;
  }
  public String getEmpName() {
      return empName;
  }
  @XmlElement
  public void setEmpName(String empName) {
      this.empName = empName;
  }
  public String getEmpPosition() {
      return empPosition;
  }
  @XmlElement
  public void setPosition(String empPosition) {
      this.empPosition = empPosition;
  }  
} 

EmployeeDao.java

package com.restexmaple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List; 

public class EmployeeDao {
  public List<Employee> getAllEmployees(){
     
      List<Employee> employeeList = null;
      try {
        File file = new File("Employees.dat");
        if (!file.exists()) {
            Employee emp = new Employee(1433, "John Doe", "Manager");
            employeeList = new ArrayList<Employee>();
            employeeList.add(emp);
            saveEmployeeList(employeeList);
        }
        else{
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            employeeList = (List<Employee>) ois.readObject();
            ois.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }  
      return employeeList;
  }
  private void saveEmployeeList(List<Employee> employeeList){
      try {
        File file = new File("Employees.dat");
        FileOutputStream fos; 
        fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(employeeList);
        oos.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
  }   
}

EmployeeService.java

package com.restexmaple;
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("/EmployeeService")

public class EmployeeService { 
  EmployeeDao empDao = new EmployeeDao(); 
  @GET
  @Path("/employees")
  @Produces(MediaType.APPLICATION_XML)
  public List<Employee> getEmployeess(){
      return empDao.getAllEmployees();
  } 
}

In the above EmployeeService.java file, you must remember that we have used annotation @Path for specifying the path for web service. Additionally, we have also established a path for the specific web service method using the @Path annotation. 

Step 4: Create the Web.xml file

Lastly, we have to create the Web.xml file. The primary objective of the Web.xml file is to assign the Jersey Framework servlet for the application being developed. 

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">
  <display-name>User Management</display-name>
  <servlet>
      <servlet-name>Jersey Employee RESTful Application</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.restexample</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>Jersey Employee RESTful Application</servlet-name>
      <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>  
</web-app>

Step5: Compile and Run the Program

After writing all the above four files mentioned, you are now ready to compile ad run the program. We have used the Eclipse IDE for writing all the above programs. Therefore we need to export the above application in a war file. Later, we have to compile and run this war file in the Tomcat Apache tool. 

We will show below how to create a war file in the Eclipse IDE. 

  • On the Eclipse IDE, go to the File option, click on the Export -> We -> War File. There you have to choose your project FirstRestExample and the target folder. 
  • Later, you have to locate the FirstRestExample.war file in the Tomcat Installation Directory option’s webapps directory. And start the Tomcat application. 

After placing the war file in Tomcat’s webapps directory, you can run your application. We will use the Chrome extension, Postman, for testing our applications. The next step is to place all the employees in POSTMAN. For this purpose, use the below line of code

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees

For using the above line of code in the Tomcat Apache, use the HTTP GET method. Here is your first web service application ready. 

Messages in the RESTful Web Service API

In the RESTful API, the client and the server communicate with each other using the HTTP protocol. The communication occurs when the client sends an HTTP Request to the server, and the server replies to the client with the HTTP Response. The communication between the client and the server using the HTTP protocol is referred to as Messaging. A single HTTP message contains message data and metadata. The metadata is message information. 

Now, let us look at the HTTP Request and HTTP Response in RESTful web service API. 

HTTP Request

The client directs an HTTP request to the server. It requests the resources from the server. There are five primary parts included in an HTTP Request, Verb, URI, HTTP version, Request Header, and Request Body. The following is an HTTP Request format. 

RESTful

Let us describe each part of an HTTP Request in brief.

  1. Verb: A verb in an HTTP Request implies the four HTTP methods, GET, POST, PUT, and DELETE. 
  2. Uniform Resource Identifier (URI): The next part of an HTTP Request is a Uniform Request Identifier (URI). A URI identifies each resource uniquely. 
  3. HTTP Version: The third part of an HTTP request is an HTTP version. For instance, HTTP v1.1, where v1.1 is a version. 
  4. Request Header: The Request Header contains the message’s metadata. The metadata in the Request Header is present in the key-value pair. It may collect information, like client type, cache settings, message format, etc. 
  5. Request Body: Request Body in an HTTP Request implies the representation of the resource. 

HTTP Response

When the server obtains an HTTP Request from the client, it replies to the client with an HTTP Response. An HTTP Response involves four significant parts, Response code, HTTP Version, Response Header, and Response Body. Below is an HTTP Response format. 

7LJDQxOJWN H1AInPZtvmIWBhvSmIzT7XLAJPTv1NLdHQZ2SlM9Dw4esHi T8k9eyQCC9tCZVnrIR5nRBm5cq1uT

Let us discuss each HTTP Response part here. 

  1. Response Code:

The Response Code is also referred to as Status. When the client requests the resource from the server, the Response Code shows its status. If the status is 404, the resource is not found. If the response is ok, the status is 200. 

  1. HTTP Version:

The second part of an HTTP Response is an HTTP version. For instance, HTTP v1.1, where v1.1 is a version. 

  1. Response Header:

The header contains the HTTP Response message’s metadata in the form of a key-value pair. It may have information like server type, content length, response data, etc. 

  1. Response Body:

The Response Body includes the representation of the resource. 

In the above example of the RESTful web service API, we have put http://localhost:8080/FirstRestExample/rest/EmployeeService/employees. 

In the POSTMAN, using the HTTP GET method. When the request is sent using the GET method, we will receive an XML message as follows. For viewing an XML Response, you have to click on the Preview button. 

Content-Length -> 144
Content-Type _> application/xml
Date -> Sat, 14 Nov 2020 12:38:00 GMT
Server -> Apache-Coyote/1.1

Resource in the RESTful Web Service API

In the RESTful web service API, every content is treated as a resource. The client requests the resource, and the server provides access to a particular resource requested by the client. After giving access, the client can modify or change the resource. The resource can be HTML pages, Images, Text Files, or Business Data. 

There is a unique number for each resource in the REST architecture. This unique number is referred to as a Uniform Resource Identifier (URI). Generally, the resource in the REST architecture is represented using an XML or JSON format. Let us now watch the representation of resources in the REST architecture. 

Resource Representation in the REST architecture

The resources in the REST architecture are represented in XML or JSON formats. You can treat a REST resource as an entity in the database or as an object in object-oriented programming. Firstly, the resource is identified using its Uniform Resource Identifier (URI). Later, the standard format for representing the resource is decided. When the client requests the resource, the server forwards the resource in the form specified by the client. 

In our above RESTful example, we have an ‘employee’ as the resource. Let us see how an ‘employee’ resource is represented using an XML form. 

<employee>
<empId>1433</empId>
<empName>John Doe</empName>
<empPosition>Manager</empPosition>
</employee>

Now, we shall depict the same ‘employee’ resource in the JSON form. 

{
"empID": 1433,
"empName": "John Doe",
"empPosition": "Manager"
}

In the REST architecture, you can represent resources in any format. There are cases in the RESTful web service API where one client requests the resource in an XML form while the other client requests the same resource in the JSON form. The only significant thing in the resource representation is it should be represented in such a format that the client can understand it. 

When the resource is represented in any format, there are some prerequisites to consider. The resource format should be understandable, complete, and linkable. The client and the server in the REST architecture should acknowledge the resource representation format quickly. Any form you choose for representing the resource, it should provide the complete resource information. The resource representation format should allow the link to any other resource. 

Most of the developers use the JSON or XML form for representing the resource in the REST architecture. There are numerous tools available today for modifying the JSON or XML data. 

Addressing in the RESTful Web Service API

Addressing in the REST architecture implies locating resources that are present on the server. We know that resources are identified by their Uniform Resource Identifiers (URIs). The format of a Uniform Resource Identifier is as follows:

<protocol>://<service-name>/<ResourceType>/<ResourceID>

The URI locates a particular resource on the server. In our above example, the URI is 

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees.

We used the HTTP GET method for the above URI. 

You might be wondering about how the URI is generated. We will guide you with some straightforward rules in building the URI for any resource in the REST architecture. 

  1. When you define resources in your web services, always use the plural form. In the above RESTful web application example, we have created a resource ‘users.’
  2. You must make sure that your resource name should not contain any whitespace or special symbol, like %, $, @, etc. You can use a hyphen (-) or underscore (_) in the resource name. For instance, the correct resource name is effective_employees and not [email protected] 
  3. In the RESTful web service, URIs are case-insensitive. But, it is always better to keep the URI in lower case. 
  4. Make sure that you use any of the HTTP Verbs or methods for performing operations on resources. In the above RESTful application, we used the HTTP GET method. 
  5. The URI should be published publicly, as web services are public services. 

Let us look at an example of good and poor URI for fetching an employee. 

Poor URI

http://localhost:8080/FirstRestExample/rest/EmployeeService/getEmployee/1

Good URI

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees/1

Java(JAX-RS) in the RESTful Web Service API

JAX-RS implies Jakarta RESTful Web Services. Earlier, it was known as Java API for RESTful Web Services. JAX-RS is a Java-based API enabling users to create web services based on the REST architecture. The latest JAX-RS version is 2.0, released in 2013. This java-based API uses annotations from Java SE 5, making the development and deployment of web services more manageable. 

JAX-RS Specifications

The following are some typically used annotations for mapping a resource as a web service resource. 

  1. @GET: This specification of JAX-RS is used for fetching the resource. 
  2. @Path: @Path implies the path of the class or method included in the web service. 
  3. @DELETE: The @DELETE resource deletes a particular resource. 
  4. @POST: The above specification in JAX-RS creates a new resource. 
  5. @PUT: This JAX-RS specification is used for updating an existing resource. 
  6. @Consumes: The @Consumes JAX-RS specification represents the type of an HTTP Request.
  7. @HEAD: Another HTTP method in JAX-RS is @HEAD, which offers information about whether the method is available or not. 
  8. @QueryParam: The above specification is used to combine the query parameter, and the parameter passed to the method. 
  9. @Produces: The @Produces specification displays the type of the HTTP Response.
  10. @PathParam: The above JAX-RS specification is used for combining the path value with the parameter passed to the method. 
  11. @CookieParam: @CookieParam combines a Cookie with the parameter passed to the method. 
  12. @MatrixParam: This JAX-RS specification combines the HTTP matrix parameter with a parameter being passed to the method. 
  13. @FormParam: The form value is combined with the parameter passed to the method using @FormParam. 
  14. @HeaderParam: The HTTP header is bound with the parameter passed to the method using @HeaderParam. 
  15. @Context: @Context implies resource context. 
  16. @DefaultValue: The above JAX-RS specification assigns the parameter passed to the method with a default value. 

Statelessness and Caching the RESTful Web Service API

Statelessness

Statelessness implies the client state should not be present on the server. The client sends its context to the server. On the receipt of the context from the client, the server stores the context and uses it for further client’s requests. For instance, the client sends the session identifier to the server. Hence, the server keeps it for identifying sessions. 

Pros:

Below are some significant advantages of statelessness in the RESTful web service API.

  • Using the statelessness property, the web service processes each method request individually. 
  • The server does not hold the client’s state or previous operations. Hence, it makes the application design more simplified. 
  • The RESTful web services process virtually on the HTTP protocols. 

Cons:

  • As the server does not contain the client’s state, the web service requires more data from every request from the client. 

Caching

The client holds some resources from the server in terms of response. Therefore, the client need not have to request the server repeatedly for the same resource. This is called caching. Based on the caching information of a particular resource offered by the server, the client decides whether to cache the resource for the specific time or never to cache it. 

There is a cache-control header consisting of five significant parts, Public, Private,max-age, no-cache/no-store, and must-revalidate. Let us see each part’s description below.

  1. Public: Any component can cache a resource that is Public. 
  2. Private: Nobody is allowed to cache the resource. Only the client and the server can cache the resource. 
  3. max-age: The max-age element is calculated in seconds. It implies how long seconds the caching of the resource is valid. Once the max-age time finishes, the client has to request the resource again. 
  4. no-cache/no-store: The client cannot cache the resource.
  5. must-revalidate: The server has to revalidate the resource when the max-age time for caching finishes. 

For configuring the client’s cache, the server response involves the following headers:

  1. Date: The resource creation date and time are represented in the Date header. 
  2. Cache-Control: The cache-control header monitors caching. 
  3. Age: The age is represented in seconds. It is the time when the resource is received from the server. 
  4. Last Modified: This header displays the date and time when the resource was updated for the last time. 
  5. Expires: This header implies caching’s expiry date and time. 

HTTP Methods and their Operations in the RESTful API

In the earlier section, we have seen the HTTP methods and Their uses. This segment shall observe the HTTPS methods, their operations, and operation type in the REST architecture. 

  1. GET:

The GET HTTP method in the above RESTful application example is used for getting the employees list. We used the URI for the GET method as below:

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees

The HTTP GET method acquires the list of employees. Hence, it has a read-only operation type. 

We can also use the GET method for retrieving the Id 1 employee. The URI for retrieving the Id 1 employee is, 

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees/1

This operation is also of a read-only type. 

  1. POST:

In our RESTful application example, we have used the HTTP POST method for inserting the employee having the Id 2. The URI for inserting the employee for Id 2 is,

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees/2

The above operation type is non-idempotent. 

  1. DELETE:

We can use the HTTP DELETE method for deleting the employee with Id 1. Below is the URI for deleting the employee with Id 1.

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees/1

The DELETE operation is of the idempotent type. 

  1. HEAD:

The HEAD method in a REST architecture is used for returning the HTTP header. It does not provide the HTTP body. For our above Employee example, we can use the below URI.

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees

This operation is of read-only type. 

  1. PUT:

In the above REST Employee application, we can use the HTTP PUT method for updating the employee with Id 2. Use the below URI for updating the employee with Id 2. 

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees/2
  1. OPTIONS:

The HTTP OPTIONS methods enable you to list all the operations supported in the web service. You can use the following URI for this operation. 

http://localhost:8080/FirstRestExample/rest/EmployeeService/employees

The OPTIONS operation is of a read-only type. 

From the above HTTP methods and their operations, we can conclude that the GET operation is a read-only type. The DELETE and PUT operations are of an idempotent type. The result of these two operations remains the same, even if they are performed multiple times. 

Conclusion

The RESTful API is a REST architecture-based API that uses the HTTP methods to access and organize data. Every data in the REST architecture is considered a resource. If you desire to learn the RESTful API, this post is a complete guide for you. 

We have seen what the RESTful web service API is, how does it work, HTTP methods used in the REST architecture, and properties & constraints of the REST architecture. Later, we have depicted the environment set-up for the RESTful API. In the RESTful API environment set-up, we have set-up the JDK environment, Tomcat Apache, Eclipse IDE, and the Jersey Framework. You can observe the simple RESTful application example in this tutorial. 

Next, we have covered several elements in the RESTful web service API, like messages, statelessness, caching, resources, and addressing. We have also discussed the Java JAX-RS and its specifications. Lastly, we have seen the HTTP methods and their operations with URI and operation type. 

Recommended Articles