Saturday, June 15, 2013

Easy restful services with tapestry and tynamo-resteasy

This is part 3 of my Resteasy Tapestry with AngularJS tutorial. We will be building the restful api for this tutorial/project. I'll be trying to keep it simple with just CRUD equivalents like GET,  POST, PUT, and DELETE.

First thing first, we will be using Tynamo Resteasy for building the api. We could build our own from scratch but why re-invent the wheel? To add it, you will leverage Maven. Open up your POM file which should be on the root portion of the project and edit it:


<dependency>  
      <groupId>org.tynamo</groupId>  
      <artifactId>tapestry-resteasy</artifactId>  
      <version>0.3.1</version>  
 </dependency>    
 <dependency>  
      <groupId>org.jboss.resteasy</groupId>  
      <artifactId>resteasy-jackson-provider</artifactId>  
      <version>3.0-beta-4</version>  
 </dependency>

We need a JSON marshaller/unmarshaller, hence the resteasy-jackson-provider. We will be working with JSON, no XML. Read the Tynamo-resteasy guide for clarification on this. Now, simply clean and build the project and let Maven do its thing and get all them jars.

The next step is to create the Tapestry service that will respond to AJAX calls. In keeping with Tapestry convention, I'm putting this service inside a package. I called mine: com.demo.tangled.rest. So, it doesn't look so cluttered, I'm just showing the GET method of our restful API inside this service.
package com.demo.tangled.rest;

import com.demo.tangled.dao.contactsDAO;
import com.demo.tangled.entities.Contacts;
import org.apache.tapestry5.ioc.annotations.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("/customers")                     // URL for API call     
public class contactsResource{
    
    @Inject                             // Get that DAO service
    private ContactsDAO contactsDAO;
    
    @GET
    @Produces({"application/json"})     // Set output format to JSON
    public List<contacts> getAllContacts(){
        return contactsDAO.getAll();
    }
    .....    
}

The interesting parts of the code are the annotations. The first annotation, @Path, is the URL for API which is appended to rest sub-domain path. So, the address of this resource is http://localhost:8080/tangled/rest/customers if this was running on a local development machine. The other request methods like POST, PUT and DELETE are written in the same manner as the getAllContacts method. Notice the @GET annotation.

I have already wrote about how to make DAO services in my previous Tapestry5 tutorial.

No comments:

Post a Comment