DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. RESTful Web Service With Example

RESTful Web Service With Example

Arun Pandey takes us through RESTful web service, examples included!

Arun Pandey user avatar by
Arun Pandey
·
Sep. 20, 16 · Tutorial
Like (20)
Save
Tweet
Share
138.22K Views

Join the DZone community and get the full member experience.

Join For Free

As we all know that RESTful is most important technology for web applications. REST stands for Representational State Transfer and this is an architectural style for web services. This helps to develop lightweight, scalable, and maintainable web services. Every system over web uses resources and it can be anything — picture, video, web page, etc. and web services provide a way to access these resources.

Now let us see the working examples as below:

Required Jars:

     asm-20041228.180559.jar

     jersey-client-1.18.1.jar

     jersey-core-1.18.1.jar

     jersey-server-1.18.1.jar

     jersey-servlet-1.18.1.jar

     jsr311-api-1.1.1.jar

Put all jars under /WebContent/WEB-INF/lib folder.

Run-Time Environment: Apache Tomcat v6.0

Create a web project using eclipse as below:

Image title

The project structure will look like it does below:

Image titleNow creating the package and java class files and the project structure will be as below:

Image title

Now let us look at the implementation:

Example 1: (Using Get Method)

GetExampleService.java

package exper.rest.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

//@Path here Identifies the URI path that a resource class will serve requests for.
@Path("GetExampleService")
public class GetExampleService {

    //To process HTTP GET requests.
    @GET
    //@Path Identifies the URI path that a resource class will serve requests for.
    @Path("/name/{nm}")
    //@Produces defines the media type(s) that the methods of a resource class can produce.
    @Produces(MediaType.TEXT_HTML)
    //@PathParam injects the value of URI parameter that defined in @Path expression, into the method
    public String userName(@PathParam("nm") String name) {
        return "<html><body>" + "<Name>" + name + "</Name>" + "</body></html>";
    }

    //To process HTTP GET requests.
    @GET
    //@Path Identifies the URI path that a resource class will serve requests for.
    @Path("/address/{ad}")
    //@Produces defines the media type(s) that the methods of a resource class can produce.
    @Produces(MediaType.TEXT_HTML)
    //@PathParam injects the value of URI parameter that defined in @Path expression, into the method
    public String userAge(@PathParam("ad") String address) {
        return "<html><body>" + "<Address>" + address + "</Address>" + "</body></html>";
    }
}

GetExampleClient.java

package exper.rest.client;

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class GetExampleClient {

    public static final String BASE_URI = "http://localhost:8083/Restful-web-service";
    public static final String PATH_NAME = "/GetExampleService/name/";
    public static final String PATH_ADDRESS = "/GetExampleService/address/";

    public static void main(String[] args) {

        String name = "Arun";
        String address = "Mumbai";

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource resource = client.resource(BASE_URI);

        WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
        System.out.println("Client Response \n" + getClientResponse(nameResource));
        System.out.println("Response \n" + getResponse(nameResource) + "\n\n");

        WebResource ageResource = resource.path("rest").path(PATH_ADDRESS + address);
        System.out.println("Client Response \n" + getClientResponse(ageResource));
        System.out.println("Response \n" + getResponse(ageResource));
    }

    /**
     * Returns client response as:- GET http://localhost:8083/Restful-web-service/rest/GetExampleService/name/Arun
     * @param service
     * @return
     */
    private static String getClientResponse(WebResource resource) {
        return resource.accept(MediaType.TEXT_HTML).get(ClientResponse.class).toString();
    }

    /**
     * Returns the response as HTML
     * @param service
     * @return
     */
    private static String getResponse(WebResource resource) {
        return resource.accept(MediaType.TEXT_HTML).get(String.class);
    }
}


Example 2: (Using Post Method)

PostExampleService.java

package exper.rest.service;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

//@Path here Identifies the URI path that a resource class will serve requests for.
@Path("PostExampleService")
public class PostExampleService {

    //To process HTTP POST requests.
    @POST
    // To identifies the URI path that a resource class method will serve requests for.
    @Path("/empInfo")
    //@Produces here defines the media type(s) that the methods of a resource class can produce.
    @Produces(MediaType.TEXT_HTML)
    //@FormParam is to retrieve the Form parameter.
    public String getEmpInfo(@FormParam("name") String name, @FormParam("age") String age) {
        return name + " and " + age;
    }
}

PostExampleClient.java

package exper.rest.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;

public class PostExampleClient {

    private static final String BASE_URI = "http://localhost:8083/Restful-web-service";
    private static final String PATH_NAME = "/PostExampleService/empInfo";

    public static void main(String[] args) throws IOException {

        Map<String, String> formDataMap = new HashMap<String, String>();
        formDataMap.put("name", "Arun");
        formDataMap.put("age", "25");

        ClientResponse res = post(formDataMap);
        System.out.println("res status :: "+ res.getStatus());
        System.out.println("res :: "+ getResponse(res));      
    }

    /**
     * Post Method
     * @param formDataMap
     * @return
     */
    private static ClientResponse post(Map<String, String> formDataMap){

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource resource = client.resource(BASE_URI);

        WebResource nameResource = resource.path("rest").path(PATH_NAME);
        Form form = new Form();

        Iterator<String> itr = formDataMap.keySet().iterator();

        while(itr.hasNext()){
            String key = itr.next();
            form.add(key, formDataMap.get(key));
        }  
        ClientResponse res = nameResource.post(ClientResponse.class, form);
        System.out.println("Client Response \n" + getClientResponse(nameResource));
        return res;
    }

    /**
     * Returns client response
     * @param resource
     * @return
     */
    private static String getClientResponse(WebResource resource) {
        return resource.getURI().toString();
    }

    /**
     * Returns the response
     * @param res
     * @return
     * @throws IOException
     */
    private static String getResponse(ClientResponse res) throws IOException {      
        InputStream is = res.getEntityInputStream();
        byte[] b = new byte[20000];
        is.read(b);
        return new String(b);
    }
}

RestFul web-services need web.xml file where init "param-value" is package name where your web-services are available. See the web.xml snippet as below:

<servlet>
    <servlet-name>REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>exper.rest.service</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet> 

In below web.xml snippet the url-patern is indicating that this servlet will be able to entertain any URL which have pattern as rest/*

<servlet-mapping>
   <servlet-name>REST Service</servlet-name>
   <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>RESTFul-WebService</display-name>
  <servlet>
    <servlet-name>REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>exper.rest.service</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>REST Service</servlet-name>
    <url-pattern>/rest/*</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>

Now it is ready to run. Start the Tomcat server which you can do simply right-click on 'RESTFul-WebService' project Run As --> Run On Server
It will start the server and will deploy the project as well.

For Get Service you can run using GetExampleClient.java as java application which will give below result:

Client Response 
    GET http://localhost:8083/Restful-web-service/rest/GetExampleService/name/Arun returned a response status of 200 OK
    Response 
    <html><body><Name>Arun</Name></body></html>

    Client Response 
    GET http://localhost:8083/Restful-web-service/rest/GetExampleService/address/Mumbai returned a response status of 200 OK
    Response 
    <html><body><Address>Mumbai</Address></body></html>

Alternatively, you can directly open the browser and put the below URL and hit go you can see the similar result as above or through any HTML page which may invoke below get page.

http://localhost:8083/RESTFul-WebService/rest/GetExampleService/name/Arun

For Post Service you can run using PostExampleClient.java as java application which will give below result:

    Client Response 
    http://localhost:8083/Restful-web-service/rest/PostExampleService/empInfo
    res status :: 200
    res :: Arun and 25

Alternatively, you can post using HTML page.

Hope this will give a better understanding about REST web service API. Happy Learning!!

REST Web Protocols Web Service

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot Docker Best Practices
  • Fraud Detection With Apache Kafka, KSQL, and Apache Flink
  • Exploring the Benefits of Cloud Computing: From IaaS, PaaS, SaaS to Google Cloud, AWS, and Microsoft
  • Beginners’ Guide to Run a Linux Server Securely

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: