The Fetch API - Methods

There are a few methods I see or use regularly:

GET: Request data from the destination url with no body provided. This is the default method.

Example request made to SWAPI to retrieve data on the "Y-wing" starship:

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

PUT: Creates or replaces data at the destination url with a body provided.

POST: Sends data to destination url. Similar to PUT except calling this method more than once will send the data additional times. A common use for this is when submitting info from an HTML form.

Example using a GraphQL query to retrieve the pokedex entries for all species whose name closely resembles the name "eevee" with a Pokemon API :

fetch("https://graphqlpokemon.favware.tech/", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    query: `query ($pokemon: String!) {
          getDexEntries(pokemon: $pokemon) {
          num
          species
        }
      }`,
    variables: {
      pokemon: "eevee"
    }
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

The reason that POST is the method for this request is because this API sent a "Apollo Server supports only GET/POST requests." response when I used PUT.

Sometimes there needs to be a bit of trial-and-error before making the proper request to a server.

DELETE: Deletes the data at the destination url. No body would be provided in the request.

You can find the list of all request methods here.