Spring RestTemplate

Client-Side HTTP Accessspringleaf

We have all been in the situation where we need to access a remote API, to return JSON or XML data.  We then have to take that data and transform it, via JSON object mappers or XML unmarshallers.

Your implementation to access the respective API from your synchronous client may look something like this:

URL url = new URL(“http://some.api.com/endpoint”);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(“GET”);

BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));

Then we would convert it to an object like this, after getting the reader information into a StringBuilder object:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode response = objectMapper.readTree(sb.toString());

That works all well and good, with some exception handling sprinkled throughout, but there’s a lot of boilerplate code there, especially when dealing with the connection handling that has to be maintained and duplicated across projects.

RestTemplate

The Spring RestTemplate allows you some abstraction for the lines above, when making synchronous calls to Web endpoints.  For instance, lines 11-16 above become:

ResponseEntity jsonTree =
     restTemplate.getForEntity(href="http://some.api.com/endpoint",
                               String.class);

The 2nd parameter is the response type we should expect.  With typical REST endpoints,  JSON and XML data should be defined here by the String class.  Then with the ResponseEntity, you can call the getBody method and throw it to ther readTree method of the ObjectMapper:

JsonNode response =
      objectMapper.readTree(jsonTree.getBody());

Note that this doesn’t require the use of a StringBuilder to read the BufferedReader object, etc.  This equates into lots of time saved, as well as less code to maintain and propagated across various projects.

OAuth2RestTemplatelock

There’s also the notion of the OAuth2RestTemplate, which extends the RestTemplate with an extra layer of abstraction for authenticating with a remote API.  Of course, this is only if the API being accessed supports OAuth authorization, i.e. the ability to grant access to functionality/data/etc.  A discussion on OAuth is beyond the scope of this post.

Without the OAuth2RestTemplate, you would need to create an additional, or series of, methods/classes to execute an authorization against the remote API’s endpoint, in addition to the logic for the calls to regular endpoints.  Let’s not also forget the logic needed to make sure you have a valid authorization key to access a respective endpoint call, HTTP client, etc.

You basically need to implement your own RestTemplate class and extend it with your own OAuth2RestTemplate class.  Depending on your business requirements, you may need a class hierarchy to manage access to any one API, as well as all the fun code management that goes along with it.

With an OAuth2RestTemplate, you simply define an authentication/authorization URI and its credentials.  I like to define these clients as beans in my application configuration:

@Bean public OAuth2RestTemplate oAuthRestTemplate() {
   ClientCredentialsResourceDetails details =
         new ClientCredentialsResourceDetails();
   details.setId("AnIdentifyingKeyValue");
   details.setClientId(oAuthClientId);
   details.setClientSecret(oAuthSecret);
   details.setAccessTokenUri(oAuthTokenUri);
   details.setScope(Arrays.asList("read", "write"));
   details.setClientAuthenticationScheme(AuthenticationScheme.header);
   details.setAuthenticationScheme(AuthenticationScheme.form);

   OAuth2RestTemplate template = new OAuth2RestTemplate(details,
         new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
   return template;
}

Now you can use it just like the RestTemplate example above, and it will do the work of authenticating/authorizing your endpoint calls.

Not a comprehensive example here, but isn’t Spring fun?

Resources noted in this post:

About Rick

I am a father, husband and software engineer, trying to stay active, both in my personal and professional communities. I enjoy programming and building Web applications.
This entry was posted in java, OAuth, OpenID, REST, Spring, Web. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s