Table of contents
1.
Introduction🙋
2.
📃RESTful Methods
3.
📃Example
3.1.
📃Intern.java 
3.2.
📃InternData.java
3.3.
📃InternService.java
3.4.
📃TestClass.java 
3.5.
Output:
4.
Frequently Asked Questions❓
4.1.
What does REST stand for?
4.2.
What are RESTful web services?
4.3.
Name some HTTP Verbs.
4.4.
What do you mean by idempotent HTTP methods?
4.5.
Give examples of idempotent HTTP methods.
5.
Conclusion🔚
Last Updated: Mar 27, 2024
Medium

RESTful - Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction🙋

Do you know what REST stands for? REST is an acronym for REpresentational State Transfer. It is a web architecture, which is a procedure we follow while designing and creating a web service. It uses HTTP protocol. We create web services using REST architecture. REST is a stateless client-server architecture. When we talk about the RESTful web services architecture we consider every web service as a resource having a URI. The Client App that use REST, use HTTP methods to communicate with the web services.

restful methods

Before proceeding, read about RESTful ApplicationsRESTful Resources, and RESTful Addressing.

In this article will see various HTTP Verbs that help perform multiple resource operations. We will also see the HTTP method that we can use on the web services and will also understand the scenarios to use the methods.

📃RESTful Methods

We know that REST web services use HTTP Verbs to perform various resource operations like updation,deletion, etc. So in the following section, we will learn about these verbs and will understand what these verbs do.

We know each resource has a URI. We identify them using the URI. Designing URIs for the resource with correct convention is discussed here, have a look! Now let us proceed to see the various methods for performing operations on the resources are in the table below: 

RESTful Methods table

 

In the table, we have a term idempotent, which means that even if we make several requests, it will make no change in the server state. After calling the HTTP methods multiple times, the result will remain the same. 

Let us see an example of a RESTful web service in which we are performing CRUD operations:

📃Example

📃Intern.java 

This file only defines all the member variables. It uses get and set methods to obtain and set the variables with a value.

package com.Coding Ninjas Studio;
import java.io.Serializable;
import javax.XML.bind.annotation.XmlElement;
import javax.XML.bind.annotation.XmlRootElement;
@XmlRootElement(name = "intern")
public class Intern implements Serializable {


   private int uid;
   private String role;

   public Intern(){}

   public Intern(int uid, String role){
      this.uid = uid;
      this.role = role;
   }

   public int getUid() {
      return uid;
   }
   @XmlElement
   public void setUid(int uid) {
      this.uid = uid;
   }
   public String getRole() {
      return role;
   }
   @XmlElement
   public void setRole(String role) {
      this.role = role;
   }

   @Override
   public boolean equals(Object object){
      if(object == null){
         return false;
      }
      else if(!(object instanceof Intern)){
         return false;
      }
      else {
         Intern intern = (Intern)object;
         if(uid == intern.getUid() && role.equals(intern.getRole()))
         {
            return true;
         } 
      }
      return false;
   }
}
You can also try this code with Online Java Compiler
Run Code

📃InternData.java

This file reads input from a file if it exists else it adds a new intern. It performs read, write, update and delete operations. At last it saves the file.

package com.Coding Ninjas Studio;
import java.io.*;
import java.util.*;
public class InternsDetails {
   public List<Intern> getAllInterns(){
      List<Intern> internList = null;
      try {
         File f = new File("Interns.dat");
         if (!f.exists()) {
            Intern intern = new Intern(1, "Writer");
            internList = new ArrayList<Intern>();
            internList.add(intern);
            saveInternList(internList); 
         }
         else{
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fis);
            internList = (List<Intern>) ois.readObject();
            ois.close();
      } catch (IOException e) {
         //
      } catch (ClassNotFoundException e) {
         //
      } 
      return internList;
   }

   public Intern getIntern(int uid){
      List<Intern> interns = getAllInterns();

      for(Intern intern: interns){
         if(intern.getUid() == uid){
            return intern;
         }
      }
      return null;
   }

   public int addIntern(Intern pIntern){
      List<Intern> internList = getAllInterns();
      boolean internExists = false;
      for(Intern intern: internList){
         if(intern.getUid() == pIntern.getUid()){
            internExists = true;
            break;
         }
      } 
      if(!internExists){
         internList.add(pIntern);
         saveInternList(internList);
         return 1;
      }
      return 0;
   }

   public int updateIntern(Intern pIntern){
      List<Intern> internList = getAllInterns();
      for(Intern intern: internList){
         if(intern.getUid() == pIntern.getUid()){
            int index = internList.indexOf(intern); 
            internList.set(index, pIntern);
            saveInternList(internList);
            return 1;
         }
      } 
      return 0;
   }

   public int deleteIntern(int uid){
      List<Intern> internList = getAllInterns();
      for(Intern intern: internList){
         if(intern.getUid() == uid){
            int index = internList.indexOf(intern); 
            internList.remove(index);
            saveInternList(internList);
            return 1;   
         }
      } 
      return 0;
   }

   private void saveInternList(List<Intern> internList){
      try {
         File f = new File("Interns.dat");
         FileOutputStream fos;
         fos = new FileOutputStream(f);
         ObjectOutputStream oos = new ObjectOutputStream(fos); 
         oos.writeObject(internList);
         oos.close();
      } 
      catch (FileNotFoundException e) {
         //
      } 
      catch (IOException e) {
         //
      }
   }
}
You can also try this code with Online Java Compiler
Run Code

📃InternService.java

This file specifies a path for the web service. We use @Path notation to specify the path for the web service or for the particular web service method.

package com.Coding Ninjas Studio;
import java.io.*;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;


@Path("/InternService")
public class InternService {

   InternsDetails internsDetails = new InternsDetails();
   private static final String s_result="<output>success</output>";
   private static final String f_result="<output>failure</output>";



   @GET
   @Path("/interns")
   @Produces(MediaType.APPLICATION_XML)
   public List<Intern> getInterns(){
      return internsDetails.getAllInterns();
   }


   @GET
   @Path("/interns/{internid}")
   @Produces(MediaType.APPLICATION_XML)
   public Intern getIntern(@PathParam("internid") int internid){
      return internsDetails.getIntern(internid);
   }


   @POST
   @Path("/interns")
   @Produces(MediaType.APPLICATION_XML)
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   public String createIntern(@FormParam("uid") int uid,
      @FormParam("role") String role,
      @Context HttpServletResponse servletResponse) throws IOException{
      Intern intern = new Intern(uid, role);
      int output = internsDetails.addIntern(intern);
      if(output == 1){
         return s_result;
      }
      return f_result;
   }


   @PUT
   @Path("/interns")
   @Produces(MediaType.APPLICATION_XML)
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   public String updateIntern(@FormParam("uid") int uid,
      @FormParam("role") String role,
      @Context HttpServletResponse servletResponse) throws IOException{
      Intern intern = new Intern(uid, role);
      int output = internsDetails.updateIntern(intern);
      if(output == 1){
         return s_result;
      }
      return f_result;
   }


   @DELETE
   @Path("/interns/{internid}")
   @Produces(MediaType.APPLICATION_XML)
   public String deleteIntern(@PathParam("internid") int internid){
      int output = internsDetails.deleteIntern(internid);
      if(output == 1){
         return s_result;
      }
      return f_result;
   }


   @OPTIONS
   @Path("/interns")
   @Produces(MediaType.APPLICATION_XML)
   public String getSupportedOperations(){
      return "<operations>GET, PUT, POST, DELETE</operations>";
   }
}
You can also try this code with Online Java Compiler
Run Code

 

📃TestClass.java
 

To test these web services, we have JERSEY. it is a tool to develop and test RESTful web services. To try the web service in the above example, we now create a web service client. All of these files are required to be in the same package. 

package com.Coding Ninjas Studio;
import java.util.List;
import javax.ws.rs.*;
public class TestClass  {

   private Client client;
   private String REST_SERVICE_URL = "http://localhost:8080/CodingNinjas/rest/Coding Ninjas Studio/interns/";
   private static final String s_result="<output>success</output>";
   private static final String PASS = "pass";
   private static final String FAIL = "fail";

   private void init(){
      this.client = ClientBuilder.newClient();
   }

   public static void main(String[] args){
      TestClass test = new TestClass();
      //initialization
      test.init();
      test.testGetAllInterns();
      test.testGetIntern();
      test.testUpdateIntern();
      test.testAddIntern();
      test.testDeleteIntern();
   }

   private void testGetAllInterns(){
      GenericType<List<Intern>> l = new GenericType<List<Intern>>() {};
      List<Intern> interns = client
         .target(REST_SERVICE_URL)
         .request(MediaType.APPLICATION_XML)
         .get(l);
      String output = PASS;
      if(interns.isEmpty()){
         output = FAIL;
      }
      System.out.println("Name of the test case-> testGetAllInterns, Output: " + output );
   }

   private void testGetIntern(){
      Intern sampleIntern = new Intern();
      sampleIntern.setUid(1);

      Intern intern = client
         .target(REST_SERVICE_URL)
         .path("/{internid}")
         .resolveTemplate("internid", 1)
         .request(MediaType.APPLICATION_XML)
         .get(Intern.class);
      String output = FAIL;
      if(sampleIntern != null && sampleIntern.getUid() == intern.getUid()){
         output = PASS;
      }
      System.out.println("Name of the test case-> testGetIntern, Output: " + output );
   }

   private void testUpdateIntern(){
      Form form = new Form();
      form.param("uid", "1");
      form.param("role", "Writer");

      String callResult = client
         .target(REST_SERVICE_URL)
         .request(MediaType.APPLICATION_XML)
         .put(Entity.entity(form,
            MediaType.APPLICATION_FORM_URLENCODED_TYPE),
            String.class);
      String output = PASS;
      if(!s_result.equals(callResult)){
         output = FAIL;
      }

      System.out.println("Name of the test case-> testUpdateIntern, Output: " + output );
   }

   private void testAddIntern(){
      Form form = new Form();
      form.param("uid", "2");
      form.param("role", "Content Strategist");

      String callResult = client
         .target(REST_SERVICE_URL)
         .request(MediaType.APPLICATION_XML)
         .post(Entity.entity(form,
            MediaType.APPLICATION_FORM_URLENCODED_TYPE),
            String.class);
   
      String output = PASS;
      if(!s_result.equals(callResult)){
         output = FAIL;
      }
      System.out.println("Name of the test case-> testAddIntern, Output: " + output );
   }
 
   private void testDeleteIntern(){
      String callResult = client
         .target(REST_SERVICE_URL)
         .path("/{internid}")
         .resolveTemplate("internid", 2)
         .request(MediaType.APPLICATION_XML)
         .delete(String.class);
      String output = PASS;
      if(!s_result.equals(callResult)){
         output = FAIL;
      }

      System.out.println("Name of the test case-> testDeleteIntern, Output: " + output );
   }
}
You can also try this code with Online Java Compiler
Run Code

Output:

After executing all of these files properly, this is what you should expect on the console:


Name of the test case-> testGetAllUsers, Output: pass
Name of the test case-> testGetUser, Output: pass
Name of the test case-> testUpdateUser, Output: pass
Name of the test case-> testAddUser, Output: pass
Name of the test case-> testDeleteUser, Output: pass

Frequently Asked Questions❓

What does REST stand for?

REST is an acronym for REpresentational State Transfer.

What are RESTful web services?

The web services that use REST architecture are known as RESTful web services.

Name some HTTP Verbs.

Some HTTP Verbs are GET, PUT, DELETE, and POST.

What do you mean by idempotent HTTP methods?

In the table, we have a term idempotent, which means that even if we make several requests, it will make no change in the server state. It means that after calling the HTTP methods multiple times, the result will remain the same.

Give examples of idempotent HTTP methods.

OPTION, GET, HEAD, and PUT are some idempotent HTTP methods.

Conclusion🔚

This article was an insight into RESTful methods. We learned what REST means. We also saw different HTTP methods and what we mean by idempotent methods. Also, check out other articles like RESTful - AddressingRESTful - StatelessnessRESTful - Application, and RESTful - Resources.

Why not have a look at web technologies on Coding Ninjas Studio? Don't stop yourself here. Also, practice data structures and algorithmsinterview questionsDBMScomputer networks, and operating systems to crack the interviews of big tech giants. Explore other fields like machine learningdeep learningcomputer vision, and big data. Also, check out Interview Experiences for different companies.

Happy learning!

Live masterclass