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:


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: So, it doesn't look so cluttered, I'm just showing the GET method of our restful API inside this service.

import com.demo.tangled.dao.contactsDAO;
import com.demo.tangled.entities.Contacts;
import org.apache.tapestry5.ioc.annotations.Inject;
import java.util.List;

@Path("/customers")                     // URL for API call     
public class contactsResource{
    @Inject                             // Get that DAO service
    private ContactsDAO contactsDAO;
    @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.