Recently I had to write some Java code to consume REST services over HTTP.
I've decided to use the Client libraries of RestEasy, the framework I use most of the time to expose REST services in Java, since it also implements the official JAX-RS specification.
I am very satisfied with the annotation driven approach that the specification defines and it makes exposing REST services a very pleasant task.
But unluckily I cannot say that I like the client API the same way.
If you are lucky enough to be able to build a proxy client based on the interface implemented by the service, well, that's not bad:
import org.jboss.resteasy.client.ProxyFactory; ... // this initialization only needs to be done once per VM RegisterBuiltin.register(ResteasyProviderFactory.getInstance()); SimpleClient client = ProxyFactory.create(MyRestServiceInterface.class, "http://localhost:8081"); client.myBusinessMethod("hello world");Having a Proxy client similar to a JAX-WS one is good, I do agree. But most of the time, when we are consuming REST web service we do not have a Java interface to import.
All those Twitter, Google or whatever public rest services available out there are just HTTP endpoints.
The way to go with RestEasy in these cases is to rely on the RestEasy Manual ClientRequest API:
ClientRequest request = new ClientRequest("http://localhost:8080/some/path"); request.header("custom-header", "value"); // We're posting XML and a JAXB object request.body("application/xml", someJaxb); // we're expecting a String back ClientResponse<String> response = request.post(String.class); if (response.getStatus() == 200) // OK! { String str = response.getEntity(); }That is in my opinion a very verbose way to fetch what is most of the time, just a bunch of strings from the web. And it gets even worse if you need to include Authentication informations:
// Configure HttpClient to authenticate preemptively // by prepopulating the authentication data cache. // 1. Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // 2. Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put("com.bluemonkeydiamond.sippycups", basicAuth); // 3. Add AuthCache to the execution context BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); // 4. Create client executor and proxy httpClient = new DefaultHttpClient(); ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext); client = ProxyFactory.create(BookStoreService.class, url, executor);I have found that Rest-assured provide a much nicer API to write client invocations.
Officially the aim of the project is to create a testing and validating framework; and most of the tutorials out there are covering those aspects, like the recent Heiko Rupp's one: http://pilhuhn.blogspot.nl/2013/01/testing-rest-apis-with-rest-assured.html
I suggest yout, instead, to use it as a development tool to experiment and write REST invocation very rapidly.
What is important to know about rest-assured:
- it implements a Domain Specific Language thanks to fluid API
- it is a single Maven dependency
- it almost completely expose a shared style for both xml and json response objects
- it relies on Apache Commons Client
So, I'll show you a bunch of real world use cases and I will leave you with some good link if you want to know more.
As most of the DSL on Java, it works better if you import statically the most
important objects:
import static com.jayway.restassured.RestAssured.*; import static com.jayway.restassured.matcher.RestAssuredMatchers.*;Base usage:
get("http://api.twitter.com/1/users/show.xml").asString();
That returns:
Uh oh, some error. Yeah, we need to pass some parameter:Sorry, that page does not exist
with() .parameter("screen_name", "resteasy") .get("http://api.twitter.com/1/users/show.xml").asString();
That returns:
Much better! Now, let's say that we want only a token of this big String XML:27016395 Resteasy resteasy http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png https://si0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png jboss.org/resteasy JBoss/Red Hat REST project false 244 C0DEED 333333 0084B4 DDEEF6 C0DEED 1 Fri Mar 27 14:39:52 +0000 2009 0 http://a0.twimg.com/images/themes/theme1/bg.png https://si0.twimg.com/images/themes/theme1/bg.png false true false false 8 en false false 21 true true ...
with() .parameter("screen_name", "resteasy") .get("http://api.twitter.com/1/users/show.xml") .path("user.profile_image_url")
And here's our output:
http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png
What if it was a JSON response?
with() .parameter("screen_name", "resteasy") .get("http://api.twitter.com/1/users/show.json")
And here's our output:
{"id":27016395,"id_str":"27016395","name":"Resteasy","screen_name":"resteasy","location":"","url":null,"description":"jboss.org\/resteasy\n\nJBoss\/Red Hat REST project","protected":false,"followers_count":244,"friends_count":1,"listed_count":21,"created_at":"Fri Mar 27 14:39:52 +0000 2009","favourites_count":0,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":8,"lang":"en","status":{"created_at":"Tue Mar 23 14:48:51 +0000 2010","id":10928528312,"id_str":"10928528312","text":"Doing free webinar tomorrow on REST, JAX-RS, RESTEasy, and REST-*. Only 40 min, so its brief. http:\/\/tinyurl.com\/yz6xwek","source":"web","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorited":false,"retweeted":false},"contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/a0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png","profile_image_url_https":"https:\/\/si0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"default_profile":true,"default_profile_image":true,"following":null,"follow_request_sent":null,"notifications":null}
And the same interface undestands JSON object navigation. Note that the navigation expression does not include "user" since it was not there in the full json response:
with() .parameter("screen_name", "resteasy") .get("http://api.twitter.com/1/users/show.json") .path("profile_image_url")
And here's our output:
http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png
Now an example of Path Parameters:
with() .parameter("key", "HomoSapiens") .get("http://eol.org/api/search/{key}").asString()
Information about the http request:
get("http://api.twitter.com/1/users/show.xml").statusCode(); get("http://api.twitter.com/1/users/show.xml").statusLine();
An example of Basic Authentication:
with() .auth().basic("paolo", "xxxx") .get("http://localhost:8080/b/secured/hello") .statusLine()
An example of Multipart Form Upload
with() .multiPart("file", "test.txt", fileContent.getBytes()) .post("/upload")
Maven dependency:
com.jayway.restassured rest-assured 1.4 test
And a Groovy snippet that can be pasted and executed directly in groovyConsole thanks to Grapes fetches the dependencies and add them automatically to the classpath, that shows you JAXB support:
@Grapes([ @Grab("com.jayway.restassured:rest-assured:1.7.2") ]) import static com.jayway.restassured.RestAssured.* import static com.jayway.restassured.matcher.RestAssuredMatchers.* import javax.xml.bind.annotation.* @XmlRootElement(name = "user") @XmlAccessorType( XmlAccessType.FIELD ) class TwitterUser { String id; String name; String description; String location; @Override String toString() { return "Id: $id, Name: $name, Description: $description, Location: $location" } } println with().parameter("screen_name", "resteasy").get("http://api.twitter.com/1/users/show.xml").as(TwitterUser.class) //
This is just a brief list of the features of the library, just you an idea of how easy it is to work with it. For a further examples I suggest you to read the official pages here:
https://code.google.com/p/rest-assured/wiki/Usage
Or another good tutorial here with a sample application to play with:
http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework
Hi Paolo,
ReplyDeletenice post :-) REST-assured is indeed a very handy tool both for testing and quick checking/invoking rest services.
As a side note, I usually simply avoid any REST vs WS comment given many believes this is like a religious war, and I have basically no experience with rest. However I couldn't resist this time ;-) To me the fact you don't have a client proxy for services unless you manually write that is basically what you pay for having ditched the full contract based approach of WS (a wsdl or at least a schema of the request/response would have properly defined the api and hence allowed generating a proxy)
Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingmulesoft online training
ReplyDelete