Lab2 View and Data API Intro

(This is a continuation from the previous post: Lab1 “Hello View and Data World”)

In Lab1, we learned how to obtain an access token and got familiarized ourselves with the basics of REST call. Let’s move on, and try to upload a model and to make it ready for viewing.

To achieve this, we use the following services:

  • Authentication/v1/authenticate (same as in the Lab 1)
  • oss/v1/buckets
  • oss/v1/buckets/{bucket key}/objects/{object key}
  • viewingservice/v1/register

where oss stands for Object Storage Service.

Work Flow

The work flow of our little app is as follows:

  • Authenticate – we first obtain an access_token. We learned how to do this in the Lab1. access_token is needed to make for subsequent calls.
  • Create a “bucket” – a bucket is a container where we upload a file.
  • Upload a file – we upload a file to the bucket we created above.
  • Register the file – we then register the file for viewing.

As an example, the application may look something like the following:

2015_0305_Lab2ViewDataAPIIntro

Request and Response in the dialog were added for learning purpose.

Create Bucket – Request

Create a bucket or a container that holds a file.

URL: https://developer.api.autodesk.com/oss/v1/buckets

Supported Request Methods: POST

Request Headers:

  • Content-Type = application/json
  • Authorization = “Bearer “ + <access_token>

Required Parameters (in JSON format):

  • bucketKey
  • policy

Doc:
http://developer.api.autodesk.com/documentation/v1/vs/oss.html#oss-buckets-api

Notice here we use  JSON as a request body format. access_token is the one we obtained through the earlier authentication request step. bucketKey is the name of “bucket” or container where you will upload your file. As naming rules, the name has to be globally unique,*1 characters between 3 and 128, and lower case only.  policy is the life length of container, either “transient” (24 hours), “temporary” (30 days) and “persistent” (till removed the owner).

*1)  The naming rule is currently under discussion as I write this.  It should be added to the documentation near future. For this exercise, I’m using Registered Developer Symbol (RDS). But it just my temporary resolution at this time.

Create Bucket – Response

Here is the sample response for oss/v1/buckets:

{
“key”:”adskbucket_632216″,
“owner”:”fc4W5gVe7WNtlGq24HHE4zsSkmNBlu4z”,
“createDate”:1425525389481,
“permissions”:
[
{
“serviceId”:”fc4W5gVe7WNtlGq24HHE4zsSkmNBlu4z”,
“access”:”full”
}
],
“policyKey”:”transient”
}

Create Bucket – Sample Code

Here is the code sample to create a bucket:

 

CreateBucket

        public static string CreateBucket(string accessToken, string bucketKey, string policy)
        {
            // (1) Build request
            var client = new RestClient();
            client.BaseUrl = new System.Uri(baseApiUrl);

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

            // Request headers  
            request.AddHeader(“Authorization”, “Bearer “ + accessToken);
            request.AddHeader(“Content-Type”, “application/json”); 

            // Add JSON body.  
            request.AddJsonBody(new { bucketKey = bucketKey, policy = policy });

            // (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) Get the key (=bucket name).
            //     Not needed for our app. Just to show the deserialization
            string key = “”;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                JsonDeserializer deserial = new JsonDeserializer();
                OssBucketsResponse bucketsResponse =
                    deserial.Deserialize<OssBucketsResponse>(response);
                key = bucketsResponse.key;
            }

            return key; // the bucket name
        }

where OssBucketResponse is defined as follows:

OssBucketsResponse
    public class OssBucketsResponse
    {
        public string key { get; set; }
        public string owner { get; set; }   
        public string createdDate { get; set; }
        public string permissions { get; set; } // TBD: as needed. 
        public string policy { get; set; }
    }

(Note: I’m only taking the top level data types for simplicity here. You can add other data types as your program requires them.)

Upload File – Request

Upload a file to a bucket.

URL: https://developer.api.autodesk.com/oss/v1/buckets/{bucketKey}/objects/{objectKey}

Supported Request Methods: POST

Url Segment Parameter:

  • bucketKey (= bucket name)
  • objectKey (= file name)

Request Headers:

  • Content-Type = “application/octet-stream”
  • Authorization = “Bearer “ + < access_token >

Required Parameters:

  • requestBody (= byte data)

Doc:

http://developer.api.autodesk.com/documentation/v1/vs/oss.html#oss-upload-api

In this call, we are using Url segment parameters; i.e., parameters in { } in the url will be replaced by the value. bucketKey is the name of the bucket that we defined in the previous step.  objectKey is the name of the file that we are uploading. Content type is “application/octet-stream”. requestBody is the actual data in byte array.

Upload File – Response

Here is the example of file upload response:

{
“bucket-key” : “adskbucket_64110”,
“objects” :
[
{
 “id” : “urn:adsk.objects:os.object:adskbucket_64110/test.rvt”,
“key” : “test.rvt”,
“sha-1” : “02695de520fa465cef80b8e2240bc2bc620fd3ca”,
“size” : 6758400,
“content-type” : “requestBody”,
“location” : “https://developer.api.autodesk.com/oss/v1/buckets/adskbucket_64110/objects/test.rvt&#8221;
}
]
}

What we need to retrieve from the response if the value of id (shown in brown).

Upload File – Sample Code

Here is the code sample to upload a file:

Upload

        public static string Upload(string accessToken, string bucketName, string fileName, byte[] fileData)
        {
            // (1) Build request
            var client = new RestClient();
            client.BaseUrl = new System.Uri(baseApiUrl);

            // Set resource/end point
            var request = new RestRequest();
            request.Resource = “oss/v1/buckets/{bucketKey}/objects/{objectKey}”;
            request.Method = Method.PUT;
            
            // Set UrlSegment
            request.AddUrlSegment(“bucketKey”, bucketName);
            request.AddUrlSegment(“objectKey”, fileName);

            // Add headers  
            request.AddHeader(“Authorization”, “Bearer “ + accessToken);
            request.AddHeader(“Content-Type”, “application/octet-stream”);

            // Add request body, byte array
            request.AddParameter(“requestBody”, fileData, ParameterType.RequestBody);

            // (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) Get id  
            string id = “”;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                JsonDeserializer deserial = new JsonDeserializer();
                OssBucketsObjectsResponse bucketsObjectsResponse =
                    deserial.Deserialize<OssBucketsObjectsResponse>(response);
                id = bucketsObjectsResponse.objects[0].id;
            }

            return id; // “urn:xxx”
        }

Where OssBucketObjects is defined as follows:

OssBucketsObjectsResponse

    [Serializable]
    publicclassOssBucketsObjectsResponse
    {
        publicstring bucketKey { get; set; }
        publicList<OssBucketsObject> objects { get; set; }
    }

    [Serializable]
    publicclassOssBucketsObject
    {
        publicstring id { get; set; }
        publicstring key { get; set; }
        publicstring sha1 { get; set; }
        publicstring size { get; set; }
        publicstring contentType { get; set; }
        publicstring location { get; set; }
    }

Register File – Request

Upload a file to a bucket.

URL:

https://developer.api.autodesk.com/viewingservice/v1/register

Supported Request Methods: PUT

Request Headers:

  • Content-Type = “application/json”
  • Authorization = “Bearer “ + < access_token >

Required Parameters (in JSON format):

  • urn

Doc:

http://developer.api.autodesk.com/documentation/v1/vs/viewing_service.html#viewing-service-create-bubbles-api

urn is the Base64 encoded form of id which we obtained after we uploaded a file. Base64 is used ensure the data is intact without modification during the transport. Note that urn is using JSON format, and not name=value parameter.

Register File – Response

Here is the successful response of register file:

{
“Result”:”Success”
}

We need to keep the urn (Base64) to access the file for viewing.

Register File – Sample Code

Here is the code sample to upload a file:

Register

        public static string Register(string accessToken, string id)
        {

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

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

            // Add headers
            request.AddHeader(“Authorization”, “Bearer “ + accessToken);
            request.AddHeader(“Content-Type”, “application/json”);

            // Convert urn to urn64.
            // urn = “urn:xxxxx”
            byte[] bytes = Encoding.UTF8.GetBytes(id);
            string urn64 = Convert.ToBase64String(bytes);

            // Add request parameter in JSON format  
            request.AddJsonBody(new { urn = urn64 } );

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

            return urn64;
        }

Putting Together

Add UI’s to call CreateBucket(), Upload() and Register(). For example,

buttonBucket_Click, buttonUpload_Click, buttonRegister_Click

        privatevoid buttonBucket_Click(object sender, EventArgs e)
        {
            string bucketname = textBoxBucketName.Text;
            string policy = “transient”; // transient(24h)/temporary(30days)/persistent

            // Here is the main part that we call View and Data API bucket creation.
            // return value key is the bucket name.  
            string key = ViewData.CreateBucket(m_accessToken, bucketname, policy);
        }

        privatevoid buttonUpload_Click(object sender, EventArgs e)
        {
            string bucketName = textBoxBucketName.Text;
            string path = textBoxFile.Text;
            string fileName = m_fileName;

            // Read file in byte array
            byte[] fileData = File.ReadAllBytes(path);

            // Here is the main part that we call upload  
            m_id = ViewData.Upload(m_accessToken, bucketName, fileName, fileData);

            textBoxId.Text = m_id; // “urn:xxx”
        }

        privatevoid buttonRegister_Click(object sender, EventArgs e)
        {
            // Here is the main part that we call Register  
            string m_urn64 = ViewData.Register(m_accessToken, m_id);
            textBoxUrn.Text = m_urn64;
        }

When everything goes successfully, you should keep the access_token and urn.

The viewer component is not supported in Win Forms. We will need to wait till later labs to do so. In a mean time, if you’d like to verify whether the file has been successfully uploaded at this point, you can test by going to one of the getting started page:

http://developer-autodesk.github.io/LmvQuickStart/

Enter access token in the Step 3, and urn in the step 13. Then click “View it”. If the file is loaded and registered correctly, your model appear on the page.

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

Next: Lab3 “View and Data API Web 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