Third-Party Web APIs

  1. Overview
    1. A Web Application Programming Interface or Web API is a service that a client program can interface with using HTTP
    2. A third-party web API is a service provided by a third party, which is often free but requires registering for a key to access it
      1. An API key is a unique string that the third party uses to track your requests
      2. Most third parties limit the number of requests that can be sent per minute, per hour, or per day
      3. More queries can usually be purchased with a subscription
    3. Many third-party web APIs provides access to a large data set
    4. Some popular web APIs:
      1. Flickr API (photos)
      2. Bing Web Search API
      3. Facebook Graph API (Facebook social graph)
      4. Yahoo Fantasy Sports API
      5. Last.fm Music Discovery API
      6. Joke API
      7. Trivia API
      8. Pokemon API
      9. OpenWeather API
    5. Most third-party web APIs are RESTful, meaning they use a query string or path or access the API and return the results in XML or JSON
    6. Some web APIs are SOAP-based, which is more complicated and heavily dependent on transfering XML between the client and server
  2. OMDb API
    1. OMDb API is a free web API to obtain movie information
    2. The movie data is obtained from IMDb
    3. You must obtain a free API key to use the service
    4. Example queries
      1. Example 1 - Search for all movies with the word "star" in the title

        http://www.omdbapi.com/?s=star&type=movie&apikey=APIKEY

        {
          "Search": [
            {
              "Title": "Star Wars: Episode IV - A New Hope",
              "Year": "1977",
              "imdbID": "tt0076759",
              "Type": "movie"
            },
            {
              "Title": "Star Wars: Episode V - The Empire Strikes Back",
              "Year": "1980",
              "imdbID": "tt0080684",
              "Type": "movie"
            },
            etc...
            {
              "Title": "Star Trek II: The Wrath of Khan",
              "Year": "1982",
              "imdbID": "tt0084726",
              "Type": "movie"
            }
          ]
        }
        
      2. Example 2 - Get info for movie with IMDB ID tt0076759 (returns JSON)

        http://www.omdbapi.com/?i=tt0076759&apikey=APIKEY

        {  
           "Title":"Star Wars: Episode IV - A New Hope",
           "Year":"1977",
           "Rated":"PG",
           "Released":"25 May 1977",
           "Runtime":"121 min",
           "Genre":"Action, Adventure, Fantasy",
           "Director":"George Lucas",
           "Writer":"George Lucas",
           "Actors":"Mark Hamill, Harrison Ford, Carrie Fisher, Peter Cushing",
           "Plot":"Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a Wookiee, and two droids to save the galaxy from the Empire's world-destroying battle-station, while also attempting to rescue Princess Leia from the evil Darth Vader.",
           "Language":"English",
           "Country":"USA",
           "Awards":"Won 6 Oscars. Another 50 wins & 28 nominations.",
           "Poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BZDk2NmNhZDgtZDgzZS00NTRkLWFiYjUtNGMzZTYwNTFhYjFmXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg",
           "Ratings":[  
              {  
                 "Source":"Internet Movie Database",
                 "Value":"8.7/10"
              },
              {  
                 "Source":"Rotten Tomatoes",
                 "Value":"93%"
              },
              {  
                 "Source":"Metacritic",
                 "Value":"92/100"
              }
           ],
           "Metascore":"92",
           "imdbRating":"8.7",
           "imdbVotes":"1,009,663",
           "imdbID":"tt0076759",
           "Type":"movie",
           "DVD":"21 Sep 2004",
           "BoxOffice":"N/A",
           "Production":"20th Century Fox",
           "Website":"http://www.starwars.com/episode-iv/",
           "Response":"True"
        }
        
  3. Accessing the movie API in C#
    1. Create a class to hold JSON data
      public class Movie
      {
          // Subset of fields from the API
          public string Title { get; set; }
          public int Year { get; set; }
          public string Rated { get; set; }
      	
      	// Custom property that doesn't exist in the API
      	public string Imdb { get; set; }
      	
      	// Map API property to C# property
      	[JsonProperty(PropertyName = "imdbRating")]
          public double ImdbRating { get; set; } 
      }
      
    2. Use HttpClient to send HTTP requests and Newtonsoft.Json package (JsonConvert object) to convert JSON into an object
      public async static Task<Movie> GetMovie(string imdbId)
      {
          const string baseUrl = "http://www.omdbapi.com/";
          const string apiKey = "YOUR_API_KEY";
          Uri requestUrl = new Uri($"{baseUrl}?i={imdbId}&apiKey={apiKey}");
          Movie movie;
      
          // using statement calls Dispose() when finished with HttpClient 
          using (var httpClient = new HttpClient())
          {
              var json = await httpClient.GetStringAsync(requestUrl);
              movie = JsonConvert.DeserializeObject<Movie>(json);
          }
      
          return movie;
      }
      
    3. Example call displays "Star Wars"
      private async void fetchButton_Click(object sender, RoutedEventArgs e)
      {
          Movie movie = await GetMovie("tt0076759");
          movieListView.Text = movie.Title;
      }
      
    4. Alternative way to deserialize with dynamic
      private async void fetchButton_Click(object sender, RoutedEventArgs e)
      dynamic apiObj = JsonConvert.DeserializeObject(json);
      movie = new Movie
      {
      	Title = apiObj.Title,
      	Year = apiObj.Year,
      	Rated = apiObj.Rated,
      	Imdb = $"IMDb rating: {apiObj.imdbRating} ({apiObj.imdbVotes} votes)"
      };
      
    5. See the MovieApiDemo UWP app