The Fetch API - Intro

The Fetch API hasn't been something I've used very much before. Even when I was using GraphQL APIs, I was learning how to use Vue Apollo for requesting data. The thought of using a built in JavaScript library didn't really occur to me.

Making an API request can be rather simple if all you need is to provide a url and the method GET to get data sent back as a response.

In this example I'm using the Star Wars API to get the planet "Tatooine".

fetch("https://swapi.dev/api/planets/1/", {
  method: "GET"
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

The data logged to the console:

{
    "name": "Tatooine",
    "rotation_period": "23",
    "orbital_period": "304",
    "diameter": "10465",
    "climate": "arid",
    "gravity": "1 standard",
    "terrain": "desert",
    "surface_water": "1",
    "population": "200000",
    "residents": [
        "http://swapi.dev/api/people/1/",
        "http://swapi.dev/api/people/2/",
        "http://swapi.dev/api/people/4/",
        "http://swapi.dev/api/people/6/",
        "http://swapi.dev/api/people/7/",
        "http://swapi.dev/api/people/8/",
        "http://swapi.dev/api/people/9/",
        "http://swapi.dev/api/people/11/",
        "http://swapi.dev/api/people/43/",
        "http://swapi.dev/api/people/62/"
    ],
    "films": [
        "http://swapi.dev/api/films/1/",
        "http://swapi.dev/api/films/3/",
        "http://swapi.dev/api/films/4/",
        "http://swapi.dev/api/films/5/",
        "http://swapi.dev/api/films/6/"
    ],
    "created": "2014-12-09T13:50:49.641000Z",
    "edited": "2014-12-20T20:58:18.411000Z",
    "url": "http://swapi.dev/api/planets/1/"
}

I first thought to make one big post about the Fetch API and all its parts, but that's a lot of information which I'm still learning about. I'm splitting up the info in separate posts to make it more readable (and to give myself a break).

There's a lot to the Fetch API. What I'm going over are the parts I've seen before and describing how I understand them. These posts will most likely expand as I come across more uses for the Fetch API.

Fetch API Parts

  1. methods
  2. headers
  3. mode
  4. body
  5. responses