Daniel Donbavand

Documenting my Development Journey

ASP.NET Core 2.0: Implementing a 3rd Party Web API

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 specfic 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 favourite 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

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.

[Route("v1/giphy")]
    public class GiphyController : Controller
    {
        [HttpGet]
        [Route("random/{searchCritera}")]
        public IActionResult GetRandomGif(string searchCritera)
        {
            return Ok();
        }
    }

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.

        [HttpGet]
        [Route("v1/giphy/random/{searchCritera}")]
        public async Task<IActionResult> GetRandomGif(string searchCritera)
        {
            var result = await _giphyServices.GetRandomGifBasedOnSearchCritera(searchCritera);

            return Ok(result);
        }
    }

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 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 how 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

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IGiphyServices, GiphyServices>();
        }

We can then inject it into our GiphyController class constructor

 private readonly IGiphyServices _giphyServices;
        public GiphyController(IGiphyServices giphyServices)
        {
            _giphyServices = giphyServices;
        }

We are now able to call our GiphyServices class.

        [HttpGet]
        [Route("v1/giphy/random/{searchCritera}")]
        public IActionResult GetRandomGif(string searchCritera)
        {
            var result = _giphyServices.GetRandomGifBasedOnSearchCritera(searchCritera);
            return Ok();
        }

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

2018-01-13_6-16-31

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.

2018-01-13_6-48-34

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

public class GiphyModel
	{
		public IEnumerable<data> data { get; set; }
	}

DataModel

public class data
	{
		public string bitly_gif_url { get; set; }
	}

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'

public class GiphyServices : IGiphyServices
    {
        private static IGetRandomGif _getRandomGif;

        public GiphyServices(IGetRandomGif getRandomGif)
        {
            _getRandomGif = getRandomGif;
        }

        public async Task<GiphyModel> GetRandomGifBasedOnSearchCritera(string searchCritera)
        {
            return await _getRandomGif.ReturnRandomGifBasedOnTag(searchCritera);
        }
    }

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.

public class GiphyServices : IGiphyServices
    {
        private readonly IGetRandomGif _getRandomGif;
        public GiphyServices(IGetRandomGif getRandomGif)
        {
            _getRandomGif = getRandomGif;
        }
        public async Task<GiphyModel> GetRandomGifBasedOnSearchCritera(string searchCritera)
        {
            return await _getRandomGif.ReturnRandomGifBasedOnTag(searchCritera);
        }
    }

We need to ensure we have added our GetRandomGif class to our ConfigureServices method inside the startup.cs class.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IGiphyServices, GiphyServices>();
            services.AddSingleton<IGetRandomGif, GetRandomGif>();
        }

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.

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

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}

2018-01-14_12-59-25

2018-01-14_13-01-13

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
https://github.com/donbavand/Giphy

I have made a recording on YouTube, you can watch it here.

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.