Lesson Tuesday

In the last lesson, we created a GetAll() method that will return a list of all animals from our API. Now we're ready to add methods to our Animal and ApiHelper classes for retrieving a single animal's details. The methods we'll add will look quite similar to the ones we already have.

Why can't we just use the same methods and just add an id to the url string? The redundant code that we are creating doesn't look very DRY.

Even though the core functionality of our methods is the same, they return different types of data and must be separated.

Models/Animal.cs
...
namespace CretaceousClient.Models
{
  public class Animal
  {
    ...
    public static Animal GetDetails(int id)
    {
      var apiCallTask = ApiHelper.Get(id);
      var result = apiCallTask.Result;

      JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(result);
      Animal animal = JsonConvert.DeserializeObject<Animal>(jsonResponse.ToString());

      return animal;
    }
  }
}

Here, we can see three key differences between our GetDetails and GetAnimals methods.

  1. The method will return a singular animal.

  2. The method will take in the id of the animal.

  3. The API call results in a JSON object as opposed to a JSON array.

Note that we also call Get as the method of ApiHelper, not GetAll. Even though the code looks nearly identical, we still need to create a new method for it because our new code will take an argument and have a slightly different endpoint.

Models/ApiHelper.cs
...
namespace CretaceousClient.Models
{
  class ApiHelper
  {
    ...
    public static async Task<string> Get(int id)
    {
      RestClient client = new RestClient("http://localhost:5000/api");
      RestRequest request = new RestRequest($"animals/{id}", Method.GET);
      var response = await client.ExecuteTaskAsync(request);
      return response.Content;
    }
  }
}

This should still look familiar as it reflects the calls we made to the New York Times quite closely. In the next lesson, we'll cover new ground and make requests that send data rather than receive it.

Lesson 19 of 22
Last updated April 6, 2022