📃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 - Addressing, RESTful - Statelessness, RESTful - 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 algorithms, interview questions, DBMS, computer networks, and operating systems to crack the interviews of big tech giants. Explore other fields like machine learning, deep learning, computer vision, and big data. Also, check out Interview Experiences for different companies.
Happy learning!