title: C# - Formatting Yelp API Output
body: <p>So I'm brand new to APIs in general. They're exciting because I can actually start making real programs. That said, I've figured out how to get results back from Yelp. The thing is, they come back formatted like this:</p>
  
  <pre><code>{
      "businesses": [
          {
              "categories": [
                  [
                      "Local Flavor",
                      "localflavor"
                  ],
                  [
                      "Mass Media",
                      "massmedia"
                  ]
              ],
              "display_phone": "+1-415-908-3801",
              "id": "yelp-san-francisco",
              "image_url": "http://s3-media3.fl.yelpcdn.com/bphoto/nQK-6_vZMt5n88zsAS94ew/ms.jpg",
              "is_claimed": true,
              "is_closed": false,
              "location": {
                  "address": [
                      "140 New Montgomery St"
                  ],
                  "city": "San Francisco",
                  "coordinate": {
                      "latitude": 37.7867703362929,
                      "longitude": -122.399958372115
                  },
                  "country_code": "US",
                  "cross_streets": "Natoma St &amp; Minna St",
                  "display_address": [
                      "140 New Montgomery St",
                      "Financial District",
                      "San Francisco, CA 94105"
                  ],
                  "geo_accuracy": 9.5,
                  "neighborhoods": [
                      "Financial District",
                      "SoMa"
                  ],
                  "postal_code": "94105",
                  "state_code": "CA"
              },
              "mobile_url": "http://m.yelp.com/biz/yelp-san-francisco",
              "name": "Yelp",
              "phone": "4159083801",
              "rating": 2.5,
              "rating_img_url": "http://s3-media4.fl.yelpcdn.com/assets/2/www/img/c7fb9aff59f9/ico/stars/v1/stars_2_half.png",
              "rating_img_url_large": "http://s3-media2.fl.yelpcdn.com/assets/2/www/img/d63e3add9901/ico/stars/v1/stars_large_2_half.png",
              "rating_img_url_small": "http://s3-media4.fl.yelpcdn.com/assets/2/www/img/8e8633e5f8f0/ico/stars/v1/stars_small_2_half.png",
              "review_count": 7140,
              "snippet_image_url": "http://s3-media4.fl.yelpcdn.com/photo/YcjPScwVxF05kj6zt10Fxw/ms.jpg",
              "snippet_text": "What would I do without Yelp?\n\nI wouldn't be HALF the foodie I've become it weren't for this business.    \n\nYelp makes it virtually effortless to discover new...",
              "url": "http://www.yelp.com/biz/yelp-san-francisco"
          }
      ],
      "total": 2316
  }
  </code></pre>
  
  <p>I don't understand how I would separate this data out and insert proper formatting into it to display it normally on a WinForm or web page. There does not seem to be a way for me to access each piece of data. I typed "response." in the IDE in reference to the JObject, but for example, there is no bool type called response.is_closed... Here is the code for my simple program below. Obviously I'm wanting to convert this to a web app or WinForm but I'd even explore formatting it nicely in the command line window,because this data displayed this way is ugly. Thank you.</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Net;
  using System.Text;
  using CommandLine;
  using Newtonsoft.Json.Linq;
  using SimpleOAuth;
  
  /// &lt;summary&gt;
  /// Yelp API v2.0 code sample.
  /// This program demonstrates the capability of the Yelp API version 2.0
  /// by using the Search API to query for businesses by a search term and location,
  /// and the Business API to query additional information about the top result
  /// from the search query.
  ///
  /// Please refer to http://www.yelp.com/developers/documentation for the API documentation.
  ///
  /// Sample usage of the program:
  /// `YelpAPI.exe --term="bars" --location="San Francisco, CA"`
  /// &lt;/summary&gt;
  namespace YelpAPI
  {
      /// &lt;summary&gt;
      /// Class that encapsulates the logic for querying the API.
      ///
      /// Users have to set the OAuth credentials properties
      /// in order to use this class.
      /// &lt;/summary&gt;
      class YelpAPIClient
      {
          /// &lt;summary&gt;
          /// Consumer key used for OAuth authentication.
          /// This must be set by the user.
          /// &lt;/summary&gt;
          private const string CONSUMER_KEY = "CENSORED";
  
          /// &lt;summary&gt;
          /// Consumer secret used for OAuth authentication.
          /// This must be set by the user.
          /// &lt;/summary&gt;
          private const string CONSUMER_SECRET = "CENSORED";
  
          /// &lt;summary&gt;
          /// Token used for OAuth authentication.
          /// This must be set by the user.
          /// &lt;/summary&gt;
          private const string TOKEN = "CENSORED";
  
          /// &lt;summary&gt;
          /// Token secret used for OAuth authentication.
          /// This must be set by the user.
          /// &lt;/summary&gt;
          private const string TOKEN_SECRET = "CENSORED";
  
          /// &lt;summary&gt;
          /// Host of the API.
          /// &lt;/summary&gt;
          private const string API_HOST = "https://api.yelp.com";
  
          /// &lt;summary&gt;
          /// Relative path for the Search API.
          /// &lt;/summary&gt;
          private const string SEARCH_PATH = "/v2/search/";
  
          /// &lt;summary&gt;
          /// Relative path for the Business API.
          /// &lt;/summary&gt;
          private const string BUSINESS_PATH = "/v2/business/";
  
          /// &lt;summary&gt;
          /// Search limit that dictates the number of businesses returned.
          /// &lt;/summary&gt;
          private const int SEARCH_LIMIT = 3;
  
          /// &lt;summary&gt;
          /// Prepares OAuth authentication and sends the request to the API.
          /// &lt;/summary&gt;
          /// &lt;param name="baseURL"&gt;The base URL of the API.&lt;/param&gt;
          /// &lt;param name="queryParams"&gt;The set of query parameters.&lt;/param&gt;
          /// &lt;returns&gt;The JSON response from the API.&lt;/returns&gt;
          /// &lt;exception&gt;Throws WebException if there is an error from the HTTP request.&lt;/exception&gt;
          private JObject PerformRequest(string baseURL, Dictionary&lt;string, string&gt; queryParams=null)
          {
              var query = System.Web.HttpUtility.ParseQueryString(String.Empty);
  
              if (queryParams == null)
              {
                  queryParams = new Dictionary&lt;string, string&gt;();
              }
  
              foreach (var queryParam in queryParams)
              {
                  query[queryParam.Key] = queryParam.Value;
              }
  
              var uriBuilder = new UriBuilder(baseURL);
              uriBuilder.Query = query.ToString();
  
              var request = WebRequest.Create(uriBuilder.ToString());
              request.Method = "GET";
  
              request.SignRequest(
                  new Tokens {
                      ConsumerKey = CONSUMER_KEY,
                      ConsumerSecret = CONSUMER_SECRET,
                      AccessToken = TOKEN,
                      AccessTokenSecret = TOKEN_SECRET
                  }
              ).WithEncryption(EncryptionMethod.HMACSHA1).InHeader();
  
              HttpWebResponse response = (HttpWebResponse)request.GetResponse();
              var stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
              return JObject.Parse(stream.ReadToEnd());
          }
  
          /// &lt;summary&gt;
          /// Query the Search API by a search term and location.
          /// &lt;/summary&gt;
          /// &lt;param name="term"&gt;The search term passed to the API.&lt;/param&gt;
          /// &lt;param name="location"&gt;The search location passed to the API.&lt;/param&gt;
          /// &lt;returns&gt;The JSON response from the API.&lt;/returns&gt;
          public JObject Search(string term, string location)
          {
              string baseURL = API_HOST + SEARCH_PATH;
              var queryParams = new Dictionary&lt;string, string&gt;()
              {
                  { "term", term },
                  { "location", location },
                  { "limit", SEARCH_LIMIT.ToString() }
              };
              return PerformRequest(baseURL, queryParams);
          }
  
          /// &lt;summary&gt;
          /// Query the Business API by a business ID.
          /// &lt;/summary&gt;
          /// &lt;param name="business_id"&gt;The ID of the business to query.&lt;/param&gt;
          /// &lt;returns&gt;The JSON response from the API.&lt;/returns&gt;
          public JObject GetBusiness(string business_id)
          {
              string baseURL = API_HOST + BUSINESS_PATH + business_id;
              return PerformRequest(baseURL);
          }
      }
  
      /// &lt;summary&gt;
      /// Command-line options abstraction.
      /// &lt;/summary&gt;
      class Options
      {
          /// &lt;summary&gt;
          /// Gets and sets the Term property.
          /// &lt;/summary&gt;
          /// &lt;value&gt;The search term specified by the user.&lt;/value&gt;
          [Option('t', "term", DefaultValue="dinner", HelpText = "Search term")]
          public string Term { get; set; }
  
          /// &lt;summary&gt;
          /// Gets and sets the Location property.
          /// &lt;/summary&gt;
          /// &lt;value&gt;The location term specified by the user.&lt;/value&gt;
          [Option('l', "location", DefaultValue="San Francisco, CA", HelpText = "Search Location")]
          public string Location { get; set; }
      }
  
      /// &lt;summary&gt;
      /// Class that encapsulates the program entry point.
      /// &lt;/summary&gt;
      class Program
      {
          /// &lt;summary&gt;
          /// Queries the API by the input values from the user, and prints
          /// the result on the console.
          /// &lt;/summary&gt;
          /// &lt;param name="term"&gt;The search term to query.&lt;/param&gt;
          /// &lt;param name="location"&gt;The location of the business to query.&lt;/param&gt;
          public static void QueryAPIAndPrintResult(string term, string location)
          {
              var client = new YelpAPIClient();
  
              Console.WriteLine("Querying for {0} in {1}...", term, location);
  
              JObject response = client.Search(term, location);
  
              JArray businesses = (JArray)response.GetValue("businesses");
  
              if (businesses.Count == 0)
              {
                  Console.WriteLine("No businesses for {0} in {1} found.", term, location);
                  return;
              }
  
              string business_id = (string)businesses[0]["id"];
  
              Console.WriteLine(
                  "{0} businesses found, querying business info for the top result \"{1}\"...",
                  businesses.Count,
                  business_id
              );
  
              response = client.GetBusiness(business_id);
  
              Console.WriteLine(String.Format("Result for business {0} found:", business_id));        
              Console.WriteLine(response.ToString());
          }
  
          /// &lt;summary&gt;
          /// Program entry point.
          /// &lt;/summary&gt;
          /// &lt;param name="args"&gt;The command-line arguments.&lt;/param&gt;
          static void Main(string[] args)
          {
              bool exit = false;
              do
              {
                  var options = new Options();
                  string locationInput = "";
                  string businessTypeInput = "";
                  try
                  {
                      CommandLine.Parser.Default.ParseArguments(args, options);
                  }
                  catch (CommandLine.ParserException)
                  {
                      Console.Error.WriteLine("Failed to parse command line options.");
                      Console.ReadKey();
                      Environment.Exit(-1);
                  }
  
                  try
                  {
                      Console.WriteLine("Enter the location: ");
                      locationInput = Console.ReadLine();
                      Console.WriteLine("Enter the type of business:");
                      businessTypeInput = Console.ReadLine();
                      Program.QueryAPIAndPrintResult(businessTypeInput, locationInput);
                      Console.WriteLine("Would you like to search again? Y/N?");
                      if (Console.ReadLine().ToUpper() == "N")
                          exit = true;
                      else
                          exit = false;
                  }
                  catch (WebException error)
                  {
                      if (error.Response != null)
                          using (var reader = new StreamReader(error.Response.GetResponseStream()))
                          {
                              Console.Error.WriteLine("Response returned: {0}", reader.ReadToEnd());
                          }
  
                      Console.Error.WriteLine("HTTP request failed, got {0}, abort program.", error.Message);
                  }
              } while (exit == false);
                  Console.ReadKey();
                  Environment.Exit(-1);
              }
          }
      }
  </code></pre>
  
  <p>Documentation is here: <a href="https://www.yelp.com/developers/documentation/v2/search_api" rel="nofollow">https://www.yelp.com/developers/documentation/v2/search_api</a></p>
  
  <p>Which lists out all of the data I am supposed to be able to grab.</p>
  
  <p>If you want to run this, you'll need the Oauth info which you can get here: <a href="https://www.yelp.com/developers/manage_api_keys" rel="nofollow">https://www.yelp.com/developers/manage_api_keys</a></p>