RESTEasy tutorial

User Rating: 4 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive
 

RESTEasy is an portable implementation of JAX-RS specification which provides a Java API for RESTful Web Services over the HTTP protocol. The Java API for RESTful web services (JAX-RS) defines a standard annotation-driven API that helps developers to create Web services in Java and invoke it. RESTFul Web services are based on the following set of principles that are different from the SOAP based Web services

  • Addressable resources: which means that everything can be identified as a resource, and each resource is uniquely identified by a URI.
  • The use standard HTTP methods (GET, POST; PUT, DELETE) to interact with the resource.
  • Representation-oriented: you interact with services using representations of that service. A resource referenced by one URI can have different formats, as different platforms need different formats. (e.g. browsers need HTML, JavaScript needs JSON and so on).
  • Communication between the client and the endpoint is stateless. All the associated state required by the server is passed by the client in each invocation.

In this tutorial we will show a step-by-step guide how to create some simple RESTful Web services using Resteasy implementation. We assume that you are running WildFly application server. If you are running an older version of the application server, check at the end of this tutorial.

Create your first RESTful service.

Create a Maven project named rest-demo, starting with a webapp-javaee7 Maven archetype:

$ mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DarchetypeRepository=https://nexus.codehaus.org/content/repositories/snapshots -DgroupId=com.sample -DartifactId=rest-demo -Dversion=1.0 -Dpackage=com.demo -Darchetype.interactive=false --batch-mode --update-
snapshots archetype:generate

Not using Maven ? As an alternative, you can create a new Dynamic Web project with Eclipse, and point to WildFly Runtime, so you will be able to compile and deploy the project

Now include the required dependencies in your pom.xml file:

<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.wildfly.bom</groupId>
				<artifactId>jboss-javaee-7.0-with-all</artifactId>
				<version>8.0.0.Final</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>jaxrs-api</artifactId>
		</dependency>
</dependencies>

In the first example, we will recall a RESTful Web service which returns a String when a certain path is request with an HTTP GET:

package com.sample;

import javax.ws.rs.*;

@Path("tutorial")
public class HelloWorld
{

    @GET
    @Path("helloworld")
    public String helloworld() {
        return "Hello World!";
    }
}

The @Path annotation at class level is used to specify the base URL of the Web service. Then you can assign a @Path annotation at method level to specify the single action you want to invoke.

Before deploying your application you need a JAX-RS class activator, which is a class extending javax.ws.rs.core.Application and declaring the Path where JAX-RS Services will be availble:

package com.sample.activator;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {

}

In this example, if you need to invoke the helloworld service, you have to use the following URL: http://localhost:8080/rest/rest-demo/tutorial/helloworld (we suppose that the web application is named rest-demo.war)

resteasy restful web services tutorial

This would produce the classic "Hello World" message on your browser. Now let's add a parameter to our service:

@GET
@Path("helloname/{name}")
public String hello(@PathParam("name") final String name) {
  return "Hello " +name;
}

Now, we have defined the "helloname" service which accepts the {name} parameter. Now the service returns the value which is appended in the URL. Example:
http://localhost:8080/rest/rest-demo/tutorial/helloname/francesco

would return:
Hello Francesco

Returning XML from your RESTEasy services

As required by the specification, RESTEasy JAX-RS includes support for (un)marshalling JAXB annotated classes. RESTEasy provides multiple JAXB Providers.

RESTEasy will select a different provider based on the return type or parameter type used in the resource. A JAXB Provider is selected by RESTEasy when a parameter or return type is an object that is annotated with JAXB annotations (such as @XmlRootEntity or @XmlType).

For example, supposing you were to return an XML containing the Item class:

package com.sample;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Item {
	public Item() { 	}

	public Item(String description, int price) { 
            this.description = description;
            this.price = price;
	}
 
	private String description;
	private int price;

        // Getter- Setter methods

}

Now add this method to your HelloWorld service:

@GET
@Path("item")
@Produces({"application/xml"})
public Item  getItem() {

  Item item = new Item("computer",2500);

 return item;
}

When invoked, the service (http://localhost:8080/rest-demo/rest/tutorial/item)  will return the following XML:

<item>
   <description>computer</description>
   <price>2500</price>
</item>

If you need to return an array of Item, you can simply use:

@GET
@Path("itemArray")
@Produces({"application/xml"})
public Item[]  getItem() {
  Item item[] = new Item[2];
  item[0] = new Item("computer",2500);
  item[1] = new Item("chair",100);

  return item;
}  

which would return:

<collection>

   <item>
     <description>computer</description>
     <price>2500</price>
   </item>

   <item>
     <description>computer</description>
     <price>2500</price>
   </item>

</collection>

If, on the othen hand you need to use standard Java collections, you have to wrap your collection in a Wrapper class:

@GET
@Path("itemList")
@Produces({"application/xml"})
 public ItemList  getCollItems() {
  ArrayList list = new ArrayList();
  Item item1 = new Item("computer",2500);
  Item item2 = new Item("chair",100);
  Item item3 = new Item("table",200);

  list.add(item1);
  list.add(item2);
  list.add(item3);

  return new ItemList(list);
 }

Where the class ItemList wrap your collection as a class instance:

package com.sample;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import java.util.List;


@XmlRootElement(name="listing")
public class ItemList
{
    private List<Item> items;

    public ItemList()
    {
    }

    public ItemList(List<Item> items)
    {
        this.items = items;
    }

    @XmlElement(name="items")
    public List<Item> getItems()
    {
        return items;
    }
}

which produces:

<listing>

  <items>
    <description>computer</description>
    <price>2500</price>
  </items>

  <items>
    <description>chair</description>
    <price>100</price>
  </items>

  <items>
    <description>table</description>
    <price>200</price>
  </items>


</listing>