Rest Web Service: Hello Word example

Rest (Representational State Transfer) web services are gaining wide spread adoption across IT by offering an architectural style/design pattern that leverages HTTP verbs to communicate information across the network between devices/servers.  Simply put, REST is hot right now, and justifiably so. It is often seen as a light weight and more scalable alternative to its big brother SOAP web services. We’ll demonstrate how to quickly create a Hello World rest service to get you started. Let’s begin!

Technologies Needed To Start

  1. Java 1.7
  2. Eclipse Kepler
  3. Maven 3.2.5
  4. Tomcat 7

1) Use Maven to Create New Project

Create folder c:\projects . Open, command line shell and run commands:

cd c:\projects

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.example -DartifactId=jersey-rest-starter -DinteractiveMode=false

Once completed you will the see the following.

 

step1

 

2. Import Project into Eclipse

From the command line run:

cd jersey-rest-starter

mvn eclipse:eclipse

This will allow you to import the project into eclipse.

Open eclipse and import the project.

 3. Write Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.example.resources;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Path("helloworld")
public class HelloWorldResource {
 
    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Hello World!";
    }
}

 4. Start Server and Test

Start the tomcat and go to the url http://localhost:8080/jersey-rest-starter/helloworld in  your browser. You will see the message “Hello World!”

step2

Congratulations! you’ve just written a HelloWorld REST service.

 

 

Leave a reply