Lab1 Hello View and Data World

(This is a continuation from the previous post: Autodesk View and Data API Intro Overview)

In this lab, we learn the first step into the View and Data world and the basic of REST API call. This is a simple Windows Forms application written in C#. The View and Data services we use in this lab is authentication/authenticate, which is a call to obtain an authentication token required for subsequent calls.

To make REST calls, we use a library called RestSharp. We chose this as the syntax of RestSharp nicely reflects the semantics of REST call and makes it easy to read the code even if you aren’t writing in C#. Please refer to this post about how to include RestSharp library to your project.

Authenticate – Request

Authenticate creates and return an access_token, which is used for subsequent service calls.

URL: https://developer.api.autodesk.com/authentication/v1/authenticate

Supported Request Methods: Post

Required Parameters:

  • client_id
  • client_secret
  • grant_type

Documentation: http://developer.api.autodesk.com/documentation/v1/auth/authentication.html#create-an-oauth2-token

client_id and client_secret are Consumer Key and Consumer Secret respectively, which you obtained from https://developer.autodesk.com/. If you haven’t gotten them, yet, please visit the site and apply for it. Anybody can apply.

(Note: When you request for keys, it will ask you to enter Callback URL. We do not use it in our exercise. You can enter any dummy value there.)

grant_type must be “client_credentials”.

Authenticate – Response

The response to View and Data API web services requests are in JSON format. A successful response to the authenticate request looks like below:

{

“token_type”:”Bearer”,

“expires_in”:1799,

access_token“:”cPJ8IbjU4KgDj8tWkuQFjo4hzs8AN”

}

Note: line breaks are added for readability.

Authenticate – Sample Code

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

Authenticate

        public static string Authenticate()
        {
            // (1) Build request
            var client = new RestClient();
            client.BaseUrl = new System.Uri(baseApiUrl);

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

            // Set required parameters
            request.AddParameter(“client_id”, consumerKey);   
            request.AddParameter(“client_secret”, consumerSecret);  
            request.AddParameter(“grant_type”, “client_credentials”);

            // (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;

            // (3) Parse the response and get the access token.
            string accessToken = “”;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                JsonDeserializer deserial = new JsonDeserializer();
                AuthenticateResponse loginResponse =
                    deserial.Deserialize<AuthenticateResponse>(response);
                accessToken = loginResponse.access_token;
            }

            return accessToken;
        }

 

Now, let’s take a look at the code in more detail.

REST Call

To make a client REST call, we first set the base URL:

var client = new RestClient();

client.BaseUrl = new System.Uri(baseApiUrl);

The base API URL is: https://developer.api.autodesk.com/

Typically, we define the base API URL, consumer key and secret as constants somewhere else, such as in the config file.

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

var request = new RestRequest();

request.Resource = “authentication/v1/authenticate”;

request.Method = Method.POST;

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

request.AddParameter(“client_id”, consumerKey);

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();

AuthenticateResponse loginResponse =

deserial.Deserialize<AuthenticateResponse>(response);

accessToken = loginResponse.access_token;

where AuthenticateResponse is defined as:

AuthenticateResponse
    public class AuthenticateResponse 
    {
        public string token_type { get; set; }
        public string expires_in { get; set; } // expiry time in seconds(30 min)
        public string access_token { get; set; }
    }

These are the basic code that you need to make a View and Data API call.

Putting Together

Add UI to display an access token that we receive as a result of calling the above Authenticate() function. (A simple Win Form will serve out purpose for this.) As an example, your buttonToken_Click() might look something like this:

buttonLogin_Click

        private static string m_accessToken = “”;

        private void buttonToken_Click(object sender, EventArgs e)
        {
            // Here is the main part that we call ViewData authenticate
            m_accessToken = ViewData.Authenticate();

            // Show it in the form
            textBoxToken.Text = m_accessToken;
        }

Disclaimer: as our goal is to learn View and Data API, we are not going into the detail of how to build UI, such as adding a button and text fields. You may choose not to add any UI to simplify your testing.

The image below shows a sample UI. (Note: In this sample, 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 don’t show these to the user.)

2015_0303_Lab1HelloViewDataWorld

When the authenticate call succeeds, you should receive access_token as a part of response. You will be using the access_token for subsequent calls to the View and Data API. You are ready for the next steps: a series of REST calls to upload a model for viewing.

You can download the View and Data API Intro Labs code from here.

Next: Lab2 “View and Data API Intro”

Mikako

Advertisements

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