Working With REST Call…

28 / Apr / 2010 by Sachin 3 comments

Recently I got an opportunity to work on making some parts of an application RESTful with secured access. It has been a good learning experience so far and encouraged me to write a blog on it. What I have done is nothing new but I never got things at one place in clear terms. So here is my effort to shed some clarity on it and hope that it will help someone.
My development environment was grails but I think this will help all, particularly those working in grails and java.

To make an application RESTful we need to generate data at server in such a format that it is consumable by a variety of devices and here XML comes into picture. so our server must be able to send response in form of well-structured XML.

To generate XML corresponding to a domain object use

render "object" as XML

To get a customized XML from an object or multiple object we need to use the groovy markup builder

render(contentType:"text/xml"){
                 bookId(id:book?.id){
                     bookNumber(book?.bookNumber)
                     chapters(){
                         for(chapterInstance in book?.chapters) {
                             chapter(id:chapterInstance?.id){
                                 title(chapterInstance?.title)
                                }
                             }
                         }
                   }
             }

This will generate the following XML

     1001
  
        
                
           
            
                
           
       .
       .
       .
      
  

Now to send data to server using XML we use post or put method. We generally use POST to post new data and PUT to update existing data on the server.
To post data to the server I am simulating a client outside a browser (its a REST call we need to send just XML, so we must not need a browser), also to access secured services on the server(here security is provided by HTTP basic authorization) we must send authorization in the header of the HTTP request. Following groovy code simulates a very basic client sending data to server using POST.

def xml = """

"""
                    def url = new URL("url")  // URL location of your application(controller/action)
                    def connection = url.openConnection()
                    connection.setRequestProperty("Method","POST")
                    connection.setRequestProperty("Content-Type" ,"application/xml" )
                   // Set your username and password and pass authorization detail in header
		    String authorizationString = "Basic " + 'username:password'.bytes.encodeBase64().toString()
	            connection.setRequestProperty("authorization",authorizationString)
		    connection.doOutput = true
                    Writer writer = new OutputStreamWriter(connection.outputStream)
                    writer.write(xml)
                    writer.flush()
                    writer.close()
                    connection.connect()

This hits at the url specified and posts the data(xml string) to the application. at server you need to parse the data (data there is a MAP not xml. cheers..!!!), do some typecasting if required and save it to your database.

You may also need to configure your application to give a 401 Unauthorized response in case username and password are not provided. If it is not done grails will give a 302 response and redirect to login page.
(if you are using spring security acegi plugin. As was the case with me). To change to the strict HTTP Basic mechanism, you’ll need to rewire the AuthenticationEntryPoint Grails is using by adding the following to your resources.groovy file:

basicAuthenticationEntryPoint(org.springframework.security.ui.basicauth.BasicProcessingFilterEntryPoint) {
        realmName = 'Grails Realm'
    }

For further details on securing an application you can refer here .

Hope this helps.

~~Regards~~
Sachin Anand
sachin@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (3)

Leave a Reply

Your email address will not be published. Required fields are marked *