Lab1 Hello Glue World

Continuing from the previous post, our THE minimum project is called “Hello Glue World”. In this lab, we learn the first step into the Glue world and the basic of REST API call. This is a simple Windows Forms application written in C#. The Glue services we use in this lab is security/login, which is a call to sign-in to the Glue and to obtain an authentication token for subsequent calls.

To make REST calls, we use a library called RestSharp in our labs, because I found it is very easy to use and gives you a very good semantic view of what REST API is if you are new to REST API. If you are already familiar with REST API in general and thinking to use other languages of your choice for actual implementation, it might help you “read” the code that are specific to the Glue API. (If you have better suggestions, feel free to share with us.)

To use RestSharp in Microsoft Visual Studio 2012 (which I’m using), go to: [Tools] >> [Library Package Manager] >> [Manage NuGet Packages for Solution…].

2015_0108_Lab1HelloGlueWorld_VS

In [Manage NuGet Packages] dialog, search “RestSharp”, and install:

2015_0108_Lab1HelloGlueWorld_NuGet

After the installation, you will see RestSharp was referenced.

2015_0108_Lab1HelloGlueWorld_SolutionExplore

For more information about RestSharp, please refer to http://restsharp.org/

Login – Request

Login authenticates a user to the Glue platform and returns an authentication token (auth_token), which is used for subsequent service calls.

URL: https://b4.autodesk.com/api/security/v1/login.{format}

Supported Request Methods: Post

Required Parameters:

  • format
  • login_name
  • password
  • company_id
  • api_key
  • timestamp
  • signature (sig)

Documentation: https://b4.autodesk.com/api/security/v1/login/doc

Among above required parameters, login_name and password are same as Autodesk ID and should be provided by the user. The company_id is the name of the host. api_key is provided by Autodesk. Normally, api_key is specific to each company. It is shared only among people who needs it and should not be shared with others.

We’ll talk about format, timestamp and signature shortly as we look at the code.

Login – Response

After you send a request, you can receive response in one of two formats: JSON and XML. You can specify in which format you would like to receive the information against the request you sent. This is one of the parameter “format” we saw earlier.

For example, when you are requesting Login, two types of format for response looks like this:

JSON
{
“auth_token”:”76d47d99102b42e3abb12551e63d1a67″,
“user_id”:”3647s71a-3366-59a5-bf0a-3a4a998c52bd“
}

XML
<?xml version=”1.0″ encoding=”utf-8″?>
<security_login_response_v1 xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”&gt;
<auth_token>”76d47d56566b42e3abb30851e63d1a67”</auth_token>
<user_id>”36477f1a-3366-44f5-bf0a-3a4a566c52bd”</user_id>
</security_login_response_v1>

Note: for both cases above, line breaks are added for readability.

As you can see above JSON is much simpler. Indeed, due to its simplicity and light-weightedness, JSON is gaining popularity in general, too. For our little app, we are going to stick to JSON because of the same reason.

Login – Sample Code

Here is a simple code to show the basic flow of login request.  Basically, what we are doing is (1) to fill out the information which are necessary to send a request, (2) make a web request, and (3) parse the response.

Login

      public string Login(string login_name, string password)
      {
         // Calculate signature components.
         string timeStamp = Utils.GetUNIXEpochTimestamp().ToString();
         string signature = Utils.ComputeMD5Hash(apiKey + apiSecret + timeStamp);

         // (1) Build request
         var client = new RestClient();
         client.BaseUrl = baseApiUrl;

         // Set resource/end point
         var request = new RestRequest();
         request.Resource = “security/v1/login.json”;
         request.Method = Method.POST;

         // Set required parameters
         request.AddParameter(“login_name”, login_name);
         request.AddParameter(“password”, password);
         request.AddParameter(“company_id”, companyId);
         request.AddParameter(“api_key”, apiKey);
         request.AddParameter(“timestamp”, timeStamp);
         request.AddParameter(“sig”, signature);

         // (2) Execute request and get response
         IRestResponse response = client.Execute(request);

         // Save response. This is to see the response for our learning.
         m_lastResponse = response;

         // Get the auth token.
         string authToken = “Undefined”;
         if (response.StatusCode == HttpStatusCode.OK)
         {
            JsonDeserializer deserial = new JsonDeserializer();
            LoginResponse loginResponse =
                deserial.Deserialize<LoginResponse>(response);
            authToken = loginResponse.auth_token;
         }

         return authToken;

      }

Next, we will take a look at the code in more detail.

Time Stamp

To define parameters, timestamp and signature, you can use helper functions:

  • timestamp = Utils.GetUNIXEpochTimestamp()
  • signature = Utils.ComputeMD5Hash(apiKey + apiSecret + timeStamp)

Time stamp is the number of seconds since January 1st, 1970 00:00:00 GMT (the UNIX epoch). The BIM 360 Glue Platform accepts timestamps up to a configurable number of minutes on either side of the server timestamp, to accommodate reasonable clock drift. Here is the code that you can copy and paste:

GetUNIXEpochTimestamp
      public static int GetUNIXEpochTimestamp()
      {
         TimeSpan tSpan = (DateTime.UtcNow – new DateTime(1970, 1, 1));
         int timestamp = (int)tSpan.TotalSeconds;
         return timestamp;
      }

Signature

The other utility function Utils.ComputeMD5Hash() defines a signature. This calculates a hash based on MD5 message-digest algorithm. You can use .NET class System.Security.Cryptography.MD5. The Glue uses MD5 cryptographic hash of the concatenated string from API key + API secret + UNIX timestamp.

Here is an example of building a Glue API signature:

Concatenate the following information:

  • API Key: ddbf3f51b3824ecbb824ae4e65d31be4
  • API Secret: 12345678901234567890123456789012
  • UNIX Timestamp: 1305568169 – (5/16/2011 5:50:36 PM)

Then, the following is the signature base string:

  • ddbf3f51b3824ecbb824ae4e65d31be4123456789012345678901234567890121305568169

Create the MD5 cryptographic hash which is sent as the “sig” parameter:

  • b3298cf0b4dc88450d00773b4449ba51

For actual calculation of MD5, you can use the function below. It shows a hash based on MD5 message-digest algorithm, which is 128-bit (16-byte) hash value, typically expressed as 32 digit hexadecimal number. Here we use System.Securrity.Cryptogaphy.MD5. For further explanation of MD5, please refer to http://en.wikipedia.org/wiki/MD5, for example:

ComputeMD5Hash

      public static string ComputeMD5Hash(string aString)
      {
         // step 1, calculate MD5 hash from aString
         MD5 md5 = System.Security.Cryptography.MD5.Create();
         byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(aString);
         byte[] hash = md5.ComputeHash(inputBytes);

         // step 2, convert byte array to hex string
         StringBuilder sb = new StringBuilder();
         for (int i = 0; i < hash.Length; i++)
         {
            sb.Append(hash[i].ToString(“x2”));
         }
         return sb.ToString();
      }

REST Call 

Back to the Login() code, to make a client REST call, we first set the base URL:

  • var client = new RestClient();
  • client.BaseUrl = baseApiUrl;

Typically, base API URL is: https://b4.autodesk.com/api/

(Once again, we are using RestSharp library. It’s easy to use and helps us focus on understanding the logic. You may choose to use other utilities that fit your need better and you want to take advantage of.).

Next, set the request resource and method either Post or Get. e.g.,

  • var request = new RestRequest();
  • request.Resource = “security/v1/login.json”;
  • request.Method = Method.POST;

Required parameters are set using AddParameter() method, e.g.,

  • request.AddParameter(“login_name”, login_name);

Finally, call client.Execute(request) to get the response from the web service:

  • IRestResponse response = client.Execute(request);

Once you get a response, you can check the status of the response. If the status code indicates the success (i.e., OK), obtain header and response body info:

  • if (response.StatusCode == HttpStatusCode.OK) …

Parse Response 

To parse the response, you can use JsonDeserializer class:

  • JsonDeserializer deserial = new JsonDeserializer();
  • LoginResponse loginResponse =
    deserial.Deserialize<LoginResponse>(response);
  • authToken = loginResponse.auth_token;

where, LoginResponse is defined as:

LoginResponse
   public class LoginResponse
   {
      public string auth_token { get; set; }
      public string user_id { get; set; }
   }

These are the basic code that you need to make a Glue API call.

Putting Together

Add UI to get a user name and password, and call above Login() function. (A simple Win Form will serve our purpose for this.) As an example, your buttonLogin_Click() might look something like this:

buttonLogin_Click

    private static string m_authToken = “”;

    private void buttonLogin_Click(object sender, EventArgs e)
    {
       // Get the user name and password from the user.
       string userName = textBoxUserName.Text;
       string password = textBoxPassword.Text;
      
      // Here is the main part that we call Glue login
      m_authToken = glueCall.Login(userName, password);
    }

A little disclaimer here: as our goal is to learn Glue API, we are not going into too much detail of how to build UI, such as adding a button and text fields. Doing so blurs the main focus of this instruction. You may choose to hard-code without any UI if you are simply testing Glue API calls at this point.

The image below shows a sample UI. (Note: In this example, we added additional text fields, Request and Response, to show http request and response. This is for learning purpose and optional for your exercise. In your real application, you probably do not show these to the user.)

2015_0108_Lab1HelloGlueWorld_Dialog

When you are able to login successfully, you should receive auth_token as a part of response. You will be using the auth_token for any subsequent calls to the Glue. You are ready for the next lab to request a list of projects.

You can get the full code project from here.

Mikako

Leave a comment