Consuming REST Services in your Windows Store and Phone Applications
This post intends to simplify consuming Representation State Transfer(REST) services in your Windows Store and Phone applications. Using REST Web Services frees you from having to store information yourself in your application or in your own service. There are a lot of services available for your applications to consume, including music, video, food, social networking, sports and weather. The following 6 steps can be used to add any public REST Service to your application, and for this specific post we will focus on retrieving restaurant data from the Yelp REST Service.
Step 1 – Find a service that provides the information you want
What kind of data are you looking to add to your application? The list below is categorized and provides a description of the service it provides. This is by all means not a complete list, but it does focus on mostly free API’s. Keep in mind that some RESTful API’s will cost money after a certain number of requests, so read the documentation for the services to find out the rules for using it before adding it to your application.
Social
Music
Video
Sports
Weather
Reviews
Fitness & Organized Sports
General Services
Step 2 – Sign up for a developer account and Register your application
You have found a service you want to add to your application. The next step is to sign up for a developer account for the service you selected and register your application. How this works will be different depending on the type of service you want to consume and is typically documented at the developer portal for the service. Sometimes developer account and application registration are done in the same step, and for other services you first register your developer account and then add applications you want to consume the service to your developer account. In either case you want to obtain the API Access ID to use in your application.
The example below is how you would sign up for a development account to consume the Yelp API’s.
- Go to the Yelp Developer Page
- Click Get Started
- Log into Yelp, or create an account. If you are creating an account, make sure to verify the new account before going on to next step.
- For this service it requests a website URL and Description on how you will use the API. I just specified my twitter URL, and a brief description.
- You will be taken to a page containing the information needed to access the Yelp API:
Step 3 – Save your Key and Secret in a safe place
You will have received a Key, and shared secret for your application to access the service. Save these in a safe place and do not share it with anyone. I typically define a global where I can access it when needed in my application:
namespace YelpData
{
public class Globals
{
public static string YELP_CLIENT_ID = "yoursecrethere";
}
}
Step 4 – Add references to your project for consuming the Service
Now that your application is registered and you have a client Id the next step is to write some code to consume the service. Since most REST Services return data using the JavaScript Object Notation(JSON), we need a JSON library to help us out. While there could be several JSON parsers available, in this particular blog we will install the Newtonsoft JSON NuGet package. The benefit of using this package is that it will work with both Phone and Windows store applications. We will use the Package Manager Console to install the package.
From the Visual Studio Tools menu choose Library Package Manager->Package Manager Console
Make sure Package source is set to nuget.org and Default Project is set to your project
At the prompt type the following command to install Newtonsoft JSON:
Install-Package Newtonsoft.Json
NOTE: You can also install NuGet Packages to your project by right clicking your project and choosing “Manage NuGet Packages…”. You can then search the online catalog for the package you want to install.
Next, we need to add a reference to make HTTP calls to the REST Service. Some REST Services, like Facebook have dedicated libraries for requesting/receiving information. If the REST Service you are consuming does not have a dedicated library then we can use System.Net.Http. This is available by default in Windows Store application projects. For Windows Phone projects follow the steps below.
In the package manager console run the following command:
Install-Package Microsoft.Net.Http
After adding the appropriate nuget packages to the application, we need to add references to them in the code.
using Newtonsoft.Json.Linq
using System.Net.Http
Now the application is ready to make HTTP Requests to the REST Service.
Step 5 – Review the documentation for the service
All of the REST Services mentioned above will have detailed documentation on how to use the service. Some even have test sites used for testing out your requests. Make sure to follow all of the instructions for making requests to the service. Typically these involve sending a query string or JSON parameter with the client id and other information. Continuing with the Yelp Sample, lets get information, including ratings, for a specific restaurant based on its phone number. Documentation for request/response data for the Yelp Phone API Is located here:
https://www.yelp.com/developers/documentation/phone_api
Step 6 – Retrieve data from the service
Now that we have an understanding for how the Yelp API works it is time for the fun part. Typically you will want a class to wrap the API Calls since a lot of the information sent to the API will be similar. In our case the only thing that will be different is the phone number. Below is a sample class that will return data from the Yelp Phone API and write the data to the output window in the visual studio debugger.
public class YelpDataService
{
public YelpDataService()
{
}
public async Task<dynamic> GetYelpInformation(string Phone)
{
var client = new HttpClient();
string reqUri = string.Format("https://api.yelp.com/phone_search?phone={0}&ywsid={1}", Phone, Globals.YELP_CLIENT_ID);
var uri = new Uri(reqUri);
var response = await client.GetStringAsync(uri);
dynamic resultObj = JObject.Parse(response);
string dbgString = string.Format("Business Name: {0}\rCity: {1}\rBusiness Phone: {2}\rAverage Rating: {3}", resultObj.businesses[0].name, resultObj.businesses[0].city, resultObj.businesses[0].phone, resultObj.businesses[0].avg_rating);
Debug.WriteLine(dbgString);
return resultObj;
}
}
When we run this code the following will be displayed in the Visual Studio Output Window:
Conclusions
That wraps up this post on how to add REST Application services to your Windows Store and Phone applications. Remember when writing your applications that you may not need to re-invent the wheel. Instead use your favorite search engine, like bing.com, to search for existing application services you can add to your application. I hope you can take the concepts illustrated in this article and apply it to the projects you are working on. Until next time, have fun coding!
Don’t forget to follow the Windows Store Developer Solutions team on Twitter @wsdevsol. Comments are welcome, both below and on twitter.
- Bret Bentzinger(Microsoft) @awehellyeah
References
JSON - https://json.org/
Representation State transfer(REST) - https://en.wikipedia.org/wiki/REST
NuGet - https://www.nuget.org/
Comments
Anonymous
January 12, 2014
social.msdn.microsoft.com/.../2b5bcffe-17a4-4989-b2a2-efe37d28c6eeAnonymous
February 05, 2014
Hi, I published two samples on MSDN Code Sample: Consuming RESTful services on Windows Store Windows Phone apps – An alternative typed approach code.msdn.microsoft.com/Consuming-RESTful-on-10b7fa9d code.msdn.microsoft.com/Consuming-RESTful-on-df1e67e5 jive it a try! hth -gAnonymous
January 09, 2015
Any idea why calling a RESTful service from a Windows Store app results in the following inner exception message? "An Attempt was made to access a socket in a way forbidden by its access permissions....". The same REST cal works from a Windows Phone app, it's just not working from Windows Store app. Is there anything I should do to the simultor/emulator? I also noticed that with Visual Studio 2013, Windows store app is not using Hyper-V, only Phone app does. ThanksAnonymous
March 24, 2015
If you receive the error with the message "An Attempt was made to access a socket in a way forbidden by its access permissions....", you need to enable "Private Networks" under package.appxmanifest/Capabilities.Anonymous
July 05, 2015
The comment has been removed