Sunday, December 2, 2012

Mashape API - How to Consume in WP

Today I'll talk about Mashape APIs and their integration into WP project.  Before getting into more details I'll like to answer few FAQs.

Q1 : What is Mashape?
Ans: Mashape is API cloud based API hub. You can used hosted API there and can quickly develop an application.

Q2 : How can I use that in WP Application?
Ans: You can consume their API(s) using REST services in WP. (Soon, auto generated client libraries will also be supported for WP code).

Prerequisite:

1. Json Client Library: This library will be helpful to consume Json response from Mashape's AP. Download the source code and compile it for the WP version you are going to use and then add in your project and use.  

How to consume REST API in Windows Phone

For my sample app I am consuming  QR code generator API.

1. Create a WebClient Request:

WebClient client = new WebClient();

2. Set Content Type in request's Header:

client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";


3. Add Authorization Header: An authorization code is required to authenticate each request, this code can be easily generated by a tool provided at this link for all registered Mashape users





client.Headers["X-Mashape-Authorization"] = "YourAutorizationHeaderNeedToGenerateFromTool";


4. Add Data for Web Request:

StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "content", HttpUtility.UrlEncode("TestQRCode"));
postData.AppendFormat("&{0}={1}", "quality", HttpUtility.UrlEncode("L"));
postData.AppendFormat("&{0}={1}", "type", HttpUtility.UrlEncode("text"));
postData.AppendFormat("&{0}={1}", "size", HttpUtility.UrlEncode("5"));


5. Create Mashape API's URI: This URI responsible to call a specific API listed in Mashape cloud listing. You can get the URL from Mashape site as shown here


var uri = new Uri("https://mutationevent-qr-code-generator.p.mashape.com/generate.php?", UriKind.Absolute);


6. Register a Asyn Call Completed Event:

client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted)


7. Make Async http Call:

client.UploadStringAsync(uri, "POST", postData.ToString());


8. Consume Response in completed event:

void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    var client = sender as WebClient;
    client.UploadStringCompleted -= client_UploadStringCompleted;
    string response = string.Empty;
    if (!e.Cancelled)
    {
        response = HttpUtility.UrlDecode(e.Result);
    }
}

You are done!!!

A full working sample can be found at the links given below.

Source Code: WP7, WP8