Complexity in a simple API request

In this first project we are going to learn how to make an API request.

Sounds simple? Wait for it, because even a simple API request hides a lot of complexity.

We are going to use PokeApi, an open API that returns information about Pokémon.

Specifically, we are going to focus on the /pokemon endpoint.

You can visit this page to see an example response:

{
  "id": 445,
  "order": 570,
  "name": "garchomp",
  "height": 19,
  "weight": 950
  // ...and more
}

Garchomp is one of my favorite Pokémon 🙋🏼‍♂️

Make a fetch request

In plain typescript a simple API request can be implemented using async/await with fetch+json:

index.ts
const main = async () => {
  const response = await fetch("https://pokeapi.co/api/v2/pokemon/garchomp/");
  const json = await response.json();
  return json;
};

main().then(console.log);

What's wrong with this?

The above code works. With "works" I mean that it's possible for the result to be correct.

Obviously "possible" is not good enough!

That's not what building a real app is about. We want the program to always work. In practice many things can go wrong:

  • The API is down
  • The response takes 10 minutes to come back
  • The response is not a valid pokemon
  • Bad internet connection
  • Invalid authentication
  • Api limit reached
  • Api congested
  • Resource missing

You get the point. We cannot be satisfied with possibly it works.

In all these cases the current implementation is broken. The app will crash and maybe report some error somewhere.

We say that the app works for "the happy path": if everything goes as expected we get the result.

Problem is plain typescript doesn't help much with all of these.

How does effect help?

For each of the problems above there is a solution:

  • The API is down: Provide two results, one for a successful response (a pokemon), one when it fails (an error message)

  • The response takes 10 minutes to come back: set a timeout that stop the program with an error

  • The response is not a valid pokemon: report an issue with the data or provide a default Pokémon

That's where effect comes in! We are going to learn how in the following lessons.