Groovy

Grails – RESTful Webservice using JAX-RS plugin

I discussed about RESTful architecture consideration and how to build RESTful web services using Jersey JAX-RS [JSR 311]  in JAVA. Today I am going to discuss how to build the RESTful web services using Grails framework.

GRAILs framework is the platform which provides end to end solution to build web application from scratch to advance intuitive RIA web application. Grails potentially be a one-stop shop for all your enterprise application development. Grails is modular, allowing you to pick and choose which modules are applicable for your application.

Grails is based on plug-in and advocates Convention over Configuration. It provides platform to build application using various latest plug-in such as H2, JQuery, and EHCache etc. Please refer here to get more understanding on Grails

It’s very easy to configure plug-in in Grails configuration file i.e. BuildConfig.groovy. Before starting to build RESTful web service, we need to create grail application using following command.

grails_apps> grails create-app TestWSRest
| Created Grails Application at D:\Demo\grail_app\ TestWSRest

Above command will create the TestWSRest application with essential environment needed for initial application development. Once we create the grails application we have to follow below steps to install RESTful plug-in for JAX-RS

  1. Add the JAXRS plug-in in BuildConfig.grovvy
plugins {
 compile ":jaxrs:0.8"
 }

Run the install plugin command from command prompt

D:\Demo\grail_app\ TestWSRest>grails InstallPlugin jaxrs

Above command will install the Jaxrs plugin into grails project name TestWSRest

Note: JAXRS is the JSR 311 implementation plug-in for grails

Resources

As RESTful web services are based on resource oriented architect. We have to create the resource which will be mapped to URL to access these resources over HTTP.

Above command will create UserResource.groovy and UserResourceTest.groovy

D:\Demo\grails_app\\TestWSRest>grails create-resource Users
| Created file grails-app/resources/testwsrest/UsersResource.groovy
| Created file test/unit/testwsrest/UsersResourceTests.groovy
package testwsrest
 class UserService {
 //Get list of users from DB
 def getUser() {
 return User.list()
 }
 //Create User in DB
 def addUser(User user){
 user.save()
 return user
 }
 }

Above resources will map http://localhost:8080/ TestWSRest/api/users to access method getUsersRepresentation using HTTP GET method. Method name could be anything but we have to use logical name for better

Run the application

To start the application enter first run the Grails application using below command and below URL

grails run-app

The browser should now display “Hello Users “

CRUD operation using Grails RESTful web

For operating CRUD operation in User create the UserService class which will use User domain to perform CRUD operation in User table in Database

First we will create UserService which will user domain User to do RDBMS process. Here we will create two method getUser to get the list of user and addUser to insert user record in DB

package testwsrest
 class UserService {
 //Get list of users from DB
 def getUser() {
 return User.list()
 }
 //Create User in DB
 def addUser(User user){
 user.save()
 return user
 }
 }

Resources:

We will modify the existing UserResource and add the getUser with @GET annotation and createUser with @POST annotation to process GET and POST HTTP operation.

  • @Path will be user to define the location of resources
  • @Consumes and @Produces define the content type for consumes and produces respectively.
  • XML converter is the package which convert domain object to XML

Dependency Injection: We will be using Grail dependency injection to inject UserService into UserResource by just declaring the service class inside resource class. Grails framework intern use Spring dependency injection to automatically inject the services.

package testwsrest

import grails.converters.XML
 import javax.ws.rs.Consumes
 import javax.ws.rs.GET
 import javax.ws.rs.POST
 import javax.ws.rs.Path
 import javax.ws.rs.Produces

@Path('/api/users')
 @Consumes(['application/xml','application/json'])
 @Produces(['application/xml','application/json'])
 class UsersResource {
 UserService userService// automatically inject(IOC) to UserResource

@GET
 String getUsers() {
 def xml =userService.getUser() as XML
 return xml
 }

@POST
 String createUsers(User user) {
 userService.addUser(user)
 return user as XML
 }
 }

Testing

package testwsrest
 import org.grails.jaxrs.itest.IntegrationTestCase
 import org.junit.Test

import static org.junit.Assert.*

class UsersResourceTests extends IntegrationTestCase {
 @Test
 void testPostAndGet() {
 def headers = ['Content-Type':'application/json', 'Accept':'application/xml']
 def content = '{"class":"testwsrest.User","username":"Sam","password":"Hill"}'
 def expected = '[<?xml version="1.0" encoding="UTF-8"?><user id="1"><password>Hill</password><username>Sam</username></user>]]'
 def User user=new User();
 user.setUsername("John")
 user.setPassword("john@")
 // create new User
 sendRequest('/api/users', 'POST', headers, content.bytes)
 assertEquals(200, response.status)
 assertEquals(expected, response.contentAsString)
 assertTrue(response.getHeader('Content-Type').startsWith('application/xml'))
 // get users
 sendRequest('/api/users', 'GET', headers)
 assertEquals(200, response.status)
 assertEquals("[${expected}]".toString(), response.contentAsString)
 assertTrue(response.getHeader('Content-Type').startsWith('application/json'))
 }
 }

Below is the simple integration test using the IntegrationTestCase

RESTful services using Scaffolding:

The grails-jaxrs plugin supports scaffolding to generate a RESTful service interface based on domain classes. Below steps explained about the scaffolding usages

  1. Create domain class by command line
    1. D:\Demo\grails_app\\TestWSRest>grails createCommand Users
    2. Generate resource class using JAXRS plugin generateREso
      1. D:\Demo\grails_app\\TestWSRest>grails generate-resource Users

Above command will automatically generate RESTful web services based on User domain

Conclusion

In this article I discussed how to create the RESTful web service in Grails framework using JAXS plug-in. You can download full source code from download link.
 

Nitin Kumar

Nitin Kumar works as a Software Architect , predominately focus on Agile, TDD, Service Oriented Architecture, Grails and JEE. Besides working in software development, He writes technical articles and watches and studies new technologies
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button