ASP.NET Core 2.0 - Implementing A Third Party Web API

Introduction

A common task for a developer when working with or building an application is implementing and interacting with APIs.

In this post, we will look at what an API is. We will then move onto creating our own .NET Core 2.0 Web API that implements a 3rd party Web API.
 
What are 3rd Party APIs?

API is an acronym for Application Programming Interface which is a software intermediary that allows two applications to talk to each other.

There are many different types of APIs. One of the more common types is a Web API, these are often called Web Services. They provide an interface for Web applications and allow applications to connect and communicate to each other via the internet. You can create your own API for others to interact with or you can interact with others API

There are thousands of public APIs that can be used. These do things like check for weather updates, get and confirm address details, make online payments and update social media status.

An example of an API in action - if you think of any website that you have visited where you are made to fill in your address details, you start by typing your street number and name. Then, a list of addresses are displayed, you select an address and the rest of the fields are populated. Chances are that the website is using a 3rd party Web API that calls off to an address service to get you a list of known addresses that match your search criteria.

While there are many different types of APIs, this post will focus on Web APIs.

The example we are going to implement is a Giphy API https://giphy.com/. Giphy is a website that stores GIF images, when a user enters provides Giphy with specific search criteria, Giphy will try and match that to an image. This API allows us to send an Http request and receive back a GIF image URL.

What we will be covering
  • Create a Simple ASP.NET Core 2.0 Web API project

  • Search and read the API (Giphy) documentation
  • Create our Controller
  • Dependency Injection
  • Project Structure
  • Creating the Model
  • Creating a Service Class
  • Creating the GetRandomGif class
  • Running the Application
Implementing the GIPHY API Create an Empty .NET Core 2.0 Web API Project

In order to start implementing our Giphy API, we need to create a blank .NET Core Web API project.

I’ve created a YouTube tutorial ASP.NET Core 2.0: Building a Simple Web API that goes through how to create this. If you need help creating the Web API, then follow that tutorial before continuing on with the next step.

Read the API Documentation

Before we start implementing anything, it’s really important to make sure we have read the APIs documentation. The API documentation contains instructions about how to effectively use and integrate with the API.

Good API documentation will tell you about usage restrictions, what kind of input the request needs, what the output of your request will look like and other implementation details.

Unfortunately, not all APIs have good documentation, you need to work with what you get and sometimes you need to do some exploratory learning.

By reading the API documentation, you can use your favorite HTTP request client to call off to the API and view the results. Currently, I am using PostMan. By ensuring that the request you make is returning you the results you expect mean that you have understood what is needed to make the request. It will also make it easier to implement into our solution.

The URL we will be using is http://api.giphy.com/v1/gifs/search?api_key={giphyKey}&q={searchCritera}&limit=1

Giphy Links

 

  • Website: https://giphy.com/
  • Developer Website: https://developers.giphy.com/
  • Giphy Documentation: https://developers.giphy.com/docs/

 

Creating our Controller

First we add a controller that returns OK.

We then add the route [Route("v1/giphy/random/{searchCritera}")] this will allow us to hit our endpoint and pass in a value, the value will be what we want to search on.

  1. [Route("v1/giphy")]  
  2. public class GiphyController: Controller {  
  3.     [HttpGet]  
  4.     [Route("random/{searchCritera}")]  
  5.     public IActionResult GetRandomGif(string searchCritera) {  
  6.         return Ok();  
  7.     }  

 

Once we have our basic concept of what the controller and method will look like we will then be following a coding style called Wishful Programming.

Wishful programming basically means that we write code with the idea that we already have classes and methods available to us, even if we haven’t created them yet. We then create these classes and methods when we need them.

Let’s try that. We know that the controller is going to call off to a GiphyServices class, so we can write the following inside our controller. 

  1. [HttpGet]  
  2. [Route("v1/giphy/random/{searchCritera}")]  
  3. public async Task<IActionResult> GetRandomGif(string searchCritera)  
  4. {  
  5.    var result = await _giphyServices.GetRandomGifBasedOnSearchCritera(searchCritera);  
  6.    return Ok(result);  
  7.    }  
  8. }  

 

Note

Throughout this code, you will see that I will be using the async and await keywords. Asynchronous programming in C# requires a full blog post of its own. As such, I won’t go into too much detail about what it is doing. If in the meantime, you would like to know more about Asynchronous programming, then you can read more about it here.

Dependency Injection

We will be using ASP.NET Cores inbuilt dependency injection framework. I wrote a blog post a while back explaining a bit about dependency inversion, injection, and control, you can read it here Dependency Inversion

MSDN also has a good article Introduction to Dependency Injection in ASP.NET Core that is directly related to ASP.NET Core

A very simplified explanation of dependency injection is that in order to access and use methods inside classes we need to instantiate the class, we can do this by newing up the class i.e var x = new GiphyServices(); or making the class static.

Dependency injection in the way we will be using it inside our Giphy project will allow us to instantiate our classes at startup and then inject them into the constructor of each class that needs them.

Remember this is a very simplified explanation of why we are using dependency injection, it has many other uses as well.

In order to use and implement Dependency Injection, we need a class and an interface for our class i.e IGiphyServices and GiphyServices, we then add the following code to the startup.cs under the ConfigureServices method.

  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.    services.AddSingleton<IGiphyServices, GiphyServices>();  
  4.  

 

We can then inject it into our GiphyController class constructor
  1. private readonly IGiphyServices _giphyServices;  
  2. public GiphyController(IGiphyServices giphyServices)  
  3. {  
  4.    _giphyServices = giphyServices;  
  5. }   
We are now able to call our GiphyServices class.
  1. [HttpGet]  
  2. [Route("v1/giphy/random/{searchCritera}")]  
  3. public IActionResult GetRandomGif(string searchCritera)  
  4. {  
  5.    var result = _giphyServices.GetRandomGifBasedOnSearchCritera(searchCritera);  
  6.    return Ok();  
  7. }  
Creating the Project Structure

When designing and building applications, it’s important that we spend time thinking about how we are designing our application and where we put everything.

Our Giphy solution is going to have two projects inside, a Giphy.API where we will store our Controllers and a Giphy.Libs.

Inside the Libs project, we will create a services class, this will be used as the glue between calling off to our Giphy class inside the Libs project, once we receive a result we will then send it back to our controller.

We will then create a Giphy class, this will be used to implement the Giphy API. We will then hit the Giphy Endpoint and get back a gif image URL.

We will also need to create a model class inside the Libs project, this model will contain properties. Once we receive a result back from our Giphy API, we then need to deserialize the result into our model. The model will hold the GIF URL that we will then send back to the person making the request.

Below is an image of what the structure looks like



Creating the Model

A model in the case of the Giphy project is a class file, that will have one or more properties that will be used to store the results that we are being returned from the Giphy API.

We will then return this result in the model back to the user making the request.

In the Read the API Documentation section above, we found what the endpoint was that we needed to use to make the request to Giphy. The request should have returned us a JSON object similar to this.

We can work out from this result, what we want inside our model(s). While there is a lot of data returned here, we often don’t need everything that is displayed. In this case, we are going to take the bitly_gif_url property only.

When creating a model that is directly mapping to the JSON result that is returned by the API, we want to follow it’s structure i.e we create two classes one that holds an IEnumerable (Collection) with a property name data, and the second that holds a string with a property name bitly_gif_url. We do this so that we can deserialize the JSON object into the model. More to come…

GiphyModel 

  1. public class GiphyModel  
  2. {  
  3.    public IEnumerable<data> data { get; set; }  
  4. }  

 

DataModel 

  1. public class data  
  2. {  
  3.    public string bitly_gif_url { get; set; }  
  4. }   

 

Creating the Service Class

Inside the services folder, we now want to create a class called Giphy services along with a matching interface. This will be the glue that takes a request from the controller and passes it to the Giphy class, once we receive a result, we then pass that back to the controller.

Notice that our return type is the GiphyModel that we created previously. This is what we will be returning back to the controller.

Using wishful programming, we make a call off to a method in our next class that we will be creating 'GetRandomGif'

  1. public class GiphyServices: IGiphyServices {  
  2.     private static IGetRandomGif _getRandomGif;  
  3.     public GiphyServices(IGetRandomGif getRandomGif) {  
  4.         _getRandomGif = getRandomGif;  
  5.     }  
  6.     public async Task < GiphyModel > GetRandomGifBasedOnSearchCritera(string searchCritera) {  
  7.         return await _getRandomGif.ReturnRandomGifBasedOnTag(searchCritera);  
  8.     }  

 

Creating the GetRandomGif class

This class will make the call to the Giphy API endpoint and return us back a result, we will also deserialize the result using newtonsoft JSON deserialize into our GiphyModel.

Let's go ahead and create a GetRandomGif class along with an interface IGetRandomGif so we can dependency inject this class and use it inside the GiphyServices class. 

  1. public class GiphyServices: IGiphyServices {  
  2.     private readonly IGetRandomGif _getRandomGif;  
  3.     public GiphyServices(IGetRandomGif getRandomGif) {  
  4.         _getRandomGif = getRandomGif;  
  5.     }  
  6.     public async Task < GiphyModel > GetRandomGifBasedOnSearchCritera(string searchCritera) {  
  7.         return await _getRandomGif.ReturnRandomGifBasedOnTag(searchCritera);  
  8.     }  
  9. }  

 

We need to ensure we have added our GetRandomGif class to our ConfigureServices method inside the startup.cs class.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.    services.AddSingleton<IGiphyServices, GiphyServices>();  
  4.    services.AddSingleton<IGetRandomGif, GetRandomGif>();  
  5. }  

You will need to install the following nuget package “Newtonsoft.JSON” into your Giphy.Libs project 

 install-package Newtonsoft.JSON 

We are using HttpClient to make the request to the Giphy API endpoint, once we get a response we deserialize the JSON object into our Giphy model that we created earlier. 

  1. public class GetRandomGif: IGetRandomGif {  
  2.     public async Task < GiphyModel > ReturnRandomGifBasedOnTag(string searchCritera) {  
  3.         const string giphyKey = "";  
  4.         using(var client = new HttpClient()) {  
  5.             var url = new Uri($ "http://api.giphy.com/v1/gifs/search?api_key={giphyKey}&q={searchCritera}&limit=1");  
  6.             var response = await client.GetAsync(url);  
  7.             string json;  
  8.             using(var content = response.Content) {  
  9.                 json = await content.ReadAsStringAsync();  
  10.             }  
  11.             return JsonConvert.DeserializeObject < GiphyModel > (json);  
  12.         }  
  13.     }  
  14. }  

 

Note you will need to add your own Giphy API key into the giphyKey constant above.

const string giphyKey = "";

Run the Application

If we run the application, we should be able to hit our endpoint.

{localhost}/v1/giphy/random/{searchCritera} 

Summary

In this blog post, we looked at what APIs are and how they are used everywhere. A lot of companies offer Web APIs as a service, that allows us to interact and gather information from the service they are offering.

In the example above Giphy offers a GIF image service, you enter a search term and it returns you a URL to a gif related to your search.

In programming we interact with Web APIs all the time, by learning how to find and read the documentation on an API and then interact with it, is a very useful coding skill to have.

Remember, it’s really important that you read the documentation to ensure you understand what you are implementing.

You can find the working code that we built above in my GitHub repo.

If you have any questions, comments or if something doesn’t make sense, reach out to me through twitter @donbavand and I’d be more than happy to help.

I also have a YouTube channel that I am creating How-To tutorials on that you can subscribe to.