August 23, 2010

Creating a RESTful Web Service - Part 5/5

In this post we will examine how a client may interact with the RESTful service we created in part 4


REST & URIs

You use URIs to interact with a RESTful service, so lets examine what are URIs will look like.  The following URI corresponds to our read method:
  • http://localhost:8080/CustomerService/rest/customers/1

Protocol - HTTP://

We are running our RESTful service on the HTTP protocol.  This is the most commonly used protocol used with RESTful services.

Host/Port - localhost:8080

For this example we used the GlassFish application server.  I installed it locally on the default port of 8080.  This portion will vary depending upon your particular application server setup.

Context Root - /CustomerService

The context root is set when the application is deployed.  If you are using GlassFish you can use the Administration Console to find/change the context root for your application.

URL Pattern - /rest

In the WEB-INF/web.xml file we created in part 4 we specified that all URLs following the pattern "/rest/*" would correspond to our RESTful service.


    Jersey Web Application
    /rest/*


Service URI - /customers

In our CustomerService session bean we created in part 4 we specified that our RESTful service would use the path "/customers" using the @Path annotation.

@Path("/customers") 
public class CustomerService {
    ...
}

Parameter URI - /1

In the read method we specified that the URI fragment following /customers corresponds to the id parameter.
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{id}")
public Customer read(@PathParam("id") long id) {
    return entityManager.find(Customer.class, id);
}


Using a Web Browser as the Client

The easiest way to test our RESTful service is using your favourite web browser.  Simply enter the URL and the browser will render the result as XML.


Using Java SE

There currently isn't a standard set of APIs yet for interacting with JAX-RS.  However your Java SE install already has all the necessary APIs.

String uri = 
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection = 
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer = 
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();


Using Implmentation Specific APIs

While there isn't a standard set of APIs to interact with JAX-RS services, implementations like Jersey do provide APIs that are easier to use than standard Java SE.

import java.util.List;
import javax.ws.rs.core.MediaType;
import org.example.Customer;
import com.sun.jersey.api.client.*;

public class JerseyClient {

    public static void main(String[] args) {
        Client client = Client.create();
        WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");

        // Get response as String
        String string = resource.path("1")
            .accept(MediaType.APPLICATION_XML)
                .get(String.class);
        System.out.println(string);

        // Get response as Customer
        Customer customer = resource.path("1")
            .accept(MediaType.APPLICATION_XML)
                .get(Customer.class);
        System.out.println(customer.getLastName() + ", "+ customer.getFirstName());

        // Get response as List<Customer>
        List<Customer> customers = resource.path("findCustomersByCity/Any%20Town")
            .accept(MediaType.APPLICATION_XML)
                .get(new GenericType<List<Customer>>(){});
        System.out.println(customers.size());
    }

}


Summary

In this series we have combined several different Java EE technologies to create a standards based RESTful service.  In upcoming posts I'll expand on what was started here to explore what else can be done in this space.


 Further Reading

If you enjoyed this post you may also be interested in:


5 comments:

  1. Good. How about a POST and DELETE client that consumes and produces JSON/XML? I've spent the whole day looking for it. =/

    ReplyDelete

Note: Only a member of this blog may post a comment.