Over a million developers have joined DZone.

RESTful Web Service With Example

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

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
java 5 ,restful api

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}