Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

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.

Tuesday, February 1, 2011

How to sort a YouTube Query with the .NET API SDK

Having trouble sorting the .NET YouTube API video feed?

Countless sites will tell you than in order to sort your videos by the date they were published, all you need to do is set the query.OrderBy property or in some instances the query.setOrderBy property to Google.GData.YouTube.YouTubeQuery.OrderBy.Published.

While working with Intellisense, I noticed that no such values are provided by the OrderBy method. I attempted just using a string query.OrderBy = "Published" but got an error "". Likewise, I thought maybe it's a numerical Enum type and attempted query.OrderBy = 1, but still no luck.

Finally after doing a bit of trial and error, I got it to work with the string "published" (all lowercase).

query.OrderBy = "published"

You can order your videos by a couple different fields, but the string must match these options case sensitvely:

relevance
published
rating
viewCount
Notice: viewCount has an uppercase C