Anda di halaman 1dari 16

A Quick Intro to RESTful APIs

with example code using Jersey (Java/J2EE)

By Satyajit Paul on 27-Dec-2012

Introduction to RESTful Web service


REST - Representational State Transfer. Roy Fielding proposed this in the year 2000 in his doctoral dissertation.

The most important concept in REST is resources, which are identified by global IDs typically using URIs
Client applications use HTTP methods (GET/ POST/ PUT/ DELETE) to manipulate the resource or collection of resources.

A RESTful Web service is a Web service implemented using HTTP and the principles of REST. The base/root URI for the Web service such as http://host/<appcontext>/resources. The MIME type of the response data supported, which are JSON/XML/ATOM and so on. The set of operations supported by the service. (for example, POST, GET, PUT or DELETE).
CRUD operations mapped to HTTP methods C: Create POST R: Read GET U: Update PUT D: Delete DELETE

Why REST
Simple to communicate as it is HTTP Based One unique URL for one resource/operation REST supports multiple data formats(JSON/XML etc) REST has an edge when it comes to Browser as client due to support for JSON Better performance & scalability, REST reads can be cached unlike its peer SOAP Some limitations: WS-Security, ACID txns (two phase commits), doesnt have a standard messaging system

Industry Perspective
Yahoo uses REST for all their services including Flickr and del.ici.ous. Amazon Ebay provide both REST & SOAP Amazons internal usage is nearly all REST Google used to provide only SOAP for all their services, but in 2006 they deprecated in favor of REST Salesforce uses REST Facebook, Twitter, Linkedin, Digg, Foursquare all provide the API access through REST (or slight variation).

New age Tech WAR is also about API dominance where everyone wants to rule. And RESTful APIs play a critical role in the whole game.
As per programmableweb, "billionaires club" of API calls include Twitter handling 13 billion per day, up from three billion in 2010. During Dec-2012, Netflix was handling 1.4 billion per day and Klout was handling one billion API calls. eBay was handling one billion per day for the first three months of 2012. Expedia's affiliate network counts $2 billion worth of business a year via APIs. 90% of what they do is business through APIs. More than half of Salesforce.com's traffic comes through APIs. REST and JavaScript Object Notation (JSON) are the dominant protocols for APIs, saying that 96% of the protocols in social APIs are REST. JSON is used as the data format in 60% of REST APIs.

Some examples
http://localhost:8888/resources/contacts
POST:create a new contact GET: list all contacts DELETE: delete all contacts PUT: bulk update all contacts

http://localhost:8888/resources/contacts/1001
GET: get the contact 1001 PUT: update contact 1001 DELETE: delete 1001

Some Example Outputs


http://localhost:8888/resources/contacts Output: {"contact": [ {"id":"1001","name":"John Doe"}, {"id":"1002","name":"Timothy Rivera"}, {"id":"1003","name":"Jeffrey Jordan"}, {"id":"1001","name":"Satyajit Paul"} ] }

http://localhost:8888/rest/contacts/1001 Output: {"id":"1001","name":John Doe}

Now, some real world stuff


Facebook graph.facebook.com Foursquare api.foursquare.com Twitter api.twitter.com https://graph.facebook.com/ibmsmartercom merce/posts https://graph.facebook.com/satyajitp2011/po sts

Code Example
All you need from Java code perspective
Resource Class Entity Class (and probably a Dao class)

Entry into web.xml


<servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</paramname> <param-value>sample.hello.resources</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/resources /*</url-pattern> </servlet-mapping>

Hello REST example


@Path("/hello") public class HelloResource { @GET @Produces({"application/json;qs=1", "application/xml;qs=.5"}) public String sayHello() { return "Hello REST"; } }

Entity Class:Contact.java
package com.ibm.jpa.entity; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Contact { private String id; private String name; public Contact() {} public Contact(String id, String name) { this.setId(id); this.setName(name); } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } }

Dao Class:ContactDao.java
package com.ibm.jpa.dao; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.ibm.jpa.entity.Contact; public class ContactDao { public static final ContactDao INSTANCE = null; public Collection<? extends Contact> getContactList() { //DUMMY Implementation Contact contact1 = new Contact("1001", "Devendra Sahu"); Contact contact2 = new Contact("1002", "Kshitiz Saxena"); Contact contact3 = new Contact("1003", "Bhavesh Kaushal"); Contact contact4 = new Contact("1001", "Abhishek Lodha"); List<Contact> contactList = new ArrayList<Contact>(); contactList.add(contact1); contactList.add(contact2); contactList.add(contact3); contactList.add(contact4); return contactList; } public Contact getContact(String id) { //DUMMY Implementation if ( "1001".equals(id)) return new Contact("1001", "Devendra Sahu"); else if ( "1002".equals(id)) return new Contact("1002", "Kshitiz Saxena"); else if ( "1003".equals(id)) return new Contact("1003", "Bhavesh Kaushal"); else if ( "1004".equals(id)) return new Contact("1004", "Abhishek Lodha"); else return new Contact("-1", "ERROR: Invalid Enployee Id"); } public void addContact(String id, String name) { // TODO Auto-generated method stub // DO DB Operation to save the contact Contact contact = new Contact(id, name); //DUMMY: persistContact(contact); } }

Resource Class:ContactResource.java
package com.ibm.rest.impl; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.core.*; import com.ibm.jpa.dao.ContactDao; import com.ibm.jpa.entity.Contact; @Path("/contacts/") public class ContactResource { @GET @Produces({"application/json;qs=1", "application/xml;qs=.5"}) public List<Contact> getContactList() { List<Contact> contactList = new ArrayList<Contact>(); ContactDao contactDao = new ContactDao(); contactList.addAll(contactDao.getContactList()); return contactList; } @GET @Produces({"application/json;qs=1", "application/xml;qs=.5"}) @Path("{id}/") public Contact getChannelConfig( @PathParam ("id") String id) { ContactDao contactDao = new ContactDao(); Contact contact = contactDao.getContact(id); return contact; } @POST @Produces({"application/json;qs=1", "application/xml;qs=.5"}) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void addFanPageConfig( @FormParam("id") String id, @FormParam("name") String name, @Context HttpServletResponse servletResponse ) throws IOException { ContactDao contactDao = new ContactDao(); contactDao.addContact(id, name); servletResponse.sendRedirect("/"); } }

Environment Setup
http://jersey.java.net/nonav/documentation/latest/chapter_deps.html
Server
jersey-server.jar jersey-core.jar asm.jar

Client
jersey-client.jar jersey-core.jar

XML/JSON binding
jackson-core-asl.jar jackson-mapper-asl.jar jackson-jaxrs.jar jettison.jar jaxb-impl.jar jaxb-api.jar activation.jar stax-api.jar

Java Source files


C ontact.jav a

C ontactResource.jav a

ContactDao.jav a

Some important urls, topics & thoughts


Imporant URLS
http://www.ibm.com/developerworks/library/wa-aj-tomcat/ http://www.slideshare.net/apigee/restful-api-design-second-edition http://jersey.java.net/nonav/documentation/latest/chapter_deps.html http://tugdualgrall.blogspot.in/2010/02/create-and-deploy-jax-rs-rest-service.html http://spf13.com/post/soap-vs-rest/ http://geeknizer.com/rest-vs-soap-using-http-choosing-the-right-webservice-protocol/ http://techcrunch.com/2012/02/10/2011-api-trends-government-apis-quintuple-facebook-google-twittermost-popular/ Java Clients browser based javascript clients etc POST: Create DELETE: to delete etc PUT: Update Authentication using OAuth 2.0 Will the custom UI development for SI be made easy by exposing REST APIs (equivalent to XAPIs)? What it takes to do that? Facebook, twitter, Linkedin all sitting on user data. Data is fragmented. Does the key for next big thing lies in integrating everything? Is it Web 3.0?

Various Clients for REST Apis


Topics not covered

Some thoughts

Contact & Message


Email satyajit.paul@gmail.com Twitter - @satya_paul Facebook - http://www.facebook.com/satyajitp2011
And last, if you like the presentation then visit www.fanffair.com and spread the word.

Anda mungkin juga menyukai