Wednesday, April 6, 2011

Pull API response using HttpWebRequest in ASP.NET (Yelp Example)

Many ASP.NET APIs will come with classes set up to help you easily pull information (such as Google, Facebook, YouTube, etc), but sometimes, such as in the case of Yelp, you'll need to connect to a URL to pull a JSON object or string.

Here's a quick and simple say to do this:
Public Sub Form_Load() Handles Me.Load
Dim apiURL As String = "http://api.yelp.com/phone_search?phone=6785557743&ywsid=####-########_#######"
Dim uri As New Uri(apiURL)
If (uri.Scheme = uri.UriSchemeHttp) Then
Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim tmp As String = reader.ReadToEnd()
response.Close()
myLiteral.Text = tmp
End If
End Sub


What we've done here is sent a HttpWebRequest out to ping the apiURL as defined by the first line of my Form_Load sub. In this case, I took a Yelp API url (you'll need to fill in the phone number, yelp api ID), but you can use any url. This particular Yelp one will return a serialized JSON Object that I can then parse out and use the information however I want.

Desired result of this HttpResponse:


After I post my request to Yelp, I can pull their response into a stream and display it to my web page using a literal, in my case, I've used a control named 'myLiteral'.

It's really that easy and fairly simple to adapt to any kind of response you'll get.