Monday, May 12, 2014

Creating an Authentication Rest Client using Retrofit for Appnexus

Before you can make calls to any AppNexus API service or report, you must use your username and password to get an authorization token. The token remains active for 2 hours, during which you do not need to re-authenticate. This page walks you through the authentication process.

For more information on Appnexus Authentication Service refer to the following wiki entry. Since you need a username and password to access the wiki, some part of it has been reproduced here just for the sake of introducing the concept.

This post has been structured into two parts:

Part 1 explains the authentication procedure for Appnexus.
Part 2 explains the Java constructs that are required to consume this API.

Part one

The following points outlines the steps involved in authenticating before consuming any service.

Step 1. Create a JSON-formatted file including your username and password
Step 2. POST the file to the authentication service, to retrieve the authentication token.
Step 3. Use the token when making calls to API services and reports

The first two steps are specific to authentication, and the third step just mentions that we have to supply the authentication token for subsequent communication.

Authentication Request Format
 
$ cat auth
{
    "auth": {
        "username" : "USERNAME",
        "password" : "PASSWORD"
    }
}

Authentication Response Format
 
$ curl -b cookies -c cookies -X POST -d @auth 'https://api.appnexus.com/auth'
{
    "response": {
        "status": "OK",
        "token": "h20hbtptiv3vlp1rkm3ve1qig0",
        "dbg_info": {
            "instance": "13.hbapi.prod.nym1",
            "slave_hit": false,
            "db": "master",
            "time": 165.15779495239,
            "start_microtime": 1332339041.1044,
            "version": "1.11.20"
        }
    }
}

Kindly pay attention to the structure of the JSON. There is an outermost object which encapsulates the actual "response" variable, which also contains the status, required authentication token and dbg_info.

Using the Authentication Token
 
$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" 'https://api.appnexus.com/member'
 
{
    "response": {
        "members": [
            {
                "id": "1",
                "name": "Car company c\/o Ad Agency",
                "active": "1",
                "bidder_id": "2"
            }
        ]
    }
}

Part two

Since we have already explained in the previous post that we will be using Retrofit to consume the API, in the following section I will present code samples related to it.

Modelling JSON response in Java

In order to read the response JSON received from Appnexus, we need a class in Java which mirrors the same structure as the incoming JSON. This has been done using two classes, namely:

ResponseContainer<T>.java

This class acts as an outermost container, which encapsulates the actual response. Pay attention to the use of generics in this class.


 
public class ResponseContainer<T> {

 private T response;

 public ResponseContainer() {
  super();
 }

 public T getResponse() {
  return response;
 }

 public void setResponse(T response) {
  this.response = response;
 }

 @Override
 public String toString() {
  return "ResponseContainer [response=" + response + "]";
 }

}

AuthenticationResponse.java

This class has the structure of the actual response which contains the authentication token. Also note that, this class extends from AbstractResponse.java which contains the dbg_info, shown above. Since certain fields like status and dbg_info are common to all the responses, we have created this class, from which every other response could extend.

 
public class AuthenticationResponse extends AbstractResponse {

 private String token;

 public String getToken() {
  return token;
 }

 public void setToken(String token) {
  this.token = token;
 }

 @Override
 public String toString() {
  return "AuthenticationResponse [token=" + token + "]";
 }

}

Modelling JSON request in Java

Before looking into the details of the rest client itself, we should also model the request object as well. This is again similar, as the object has to mirror the request JSON. I have not enclosed the class here, but it should be quite straightforward to create one.

Retrofit Authentication Rest Client Interface

The following code sample outlines the interface that is required to talk to Appnexus using Retrofit. Pay attention to the use of @POST annotation using which the endpoint has been specified. Also observe how the request objects and the response objects we just modelled has been used.
The biggest advantage of using Retrofit is that, the contract is extremely clear and it only deals with the business in question. It totally hides away the nuances of creating HTTP related infrastructure.
 
public interface AuthenticationRestClient {

 @POST("/auth/")
 ResponseContainer<authenticationresponse> authenticate(
   @Body AuthenticationRequest authenticationRequest);
}

Creating the rest client and using it

Finally, once everything has been done, we could create an instance of AuthenticationRestClient using the following code block, and start interacting with Appnexus to fetch the authentication token.

 
RestAdapter restAdapter = new RestAdapter.Builder()
 .setEndpoint(appnexusApiEndpoint).setLogLevel(LogLevel.HEADERS).build();

// create auth client
AuthenticationRestClient authClient = restAdapter.create(AuthenticationRestClient.class);
ResponseContainer<authenticationresponse> responseContainer = authClient.authenticate(authenticationRequest);

// get the token here
String token = responseContainer.getResponse().getToken();

Conclusion

I could see that a lot of code samples has been given, they should provide enough guidance to understand the concepts outlined, if you have any difficulty in understanding how the pieces fit together, do drop a comment with the details, I'll try to clarify them. In the following post, I'll outlined the following details:

  • Details of automatically adding the authentication token in the subsequent requests.
  • Mechanisms for the using the same authentication token in all the subsequent requests until it expires and also ways to retrieve it again after it expires.

No comments :

Post a Comment