DEV Community

Cover image for What the Fetch?
rockshellS
rockshellS

Posted on

What the Fetch?

what is fetch()

fetch('https://api.punkapi.com/v2/beers')
  .then(response => response.json())
  .then(beers => console.log(beers));
Enter fullscreen mode Exit fullscreen mode

the above is a basic fetch request. it's a function in JavaScript for interacting with a database. Let me break down this code some and get a better understanding on what's going on.

fetch('https://api.punkapi.com/v2/beers')
Enter fullscreen mode Exit fullscreen mode

fetch() can take in two arguments. one mandatory argument, the URL of the resource you're looking for data from. This is the GET request. Just getting the info from the API. We will talk about the second argument a little later. Let's take a look and this first line of code. Open up your DevTools and copy paste the line above.

fetch('https://api.punkapi.com/v2/beers')
Promise {<pending>}
Enter fullscreen mode Exit fullscreen mode

Promise { pending } ? what is this? I was told that a promise is like an IOU. At some point you will be getting a response. It doesn't mean the response is what you are wanting. The response could be an error. They can be fulfilled, rejected or pending.

Let's take a look and the second line of code.

.then(resp => resp.json())
Enter fullscreen mode Exit fullscreen mode

the fetch returns it's promise with this function that has the response you requested from the API and it's putting it into json format.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. -www.json.org
we can see that the promise was fulfilled and now we have some data. An Array(25)

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(25)
Enter fullscreen mode Exit fullscreen mode

the third line of code is where you finally get to use and do things with the data.

.then(beers => console.log(beers));
Enter fullscreen mode Exit fullscreen mode

let's take a look. Put the code in DevTools and what do we get?

fetch('https://api.punkapi.com/v2/beers')
  .then(response => response.json())
  .then(beers => console.log(beers));
Promise {<pending>}
base.js:8238 
(25) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, name: "Buzz", tagline: "A Real Bitter Experience.", first_brewed: "09/2007", description: "A light, crisp and bitter IPA brewed with English and American hops. A small batch brewed only once.", …}
1: {id: 2, name: "Trashy Blonde", tagline: "You Know You Shouldn't", first_brewed: "04/2008", description: "A titillating, neurotic, peroxide punk of a Pale A…the customary BrewDog bite and imaginative twist.", …}
2: {id: 3, name: "Berliner Weisse With Yuzu - B-Sides", tagline: "Japanese Citrus Berliner Weisse.", first_brewed: "11/2015", description: "Japanese citrus fruit intensifies the sour nature of this German classic.", …}
3: {id: 4, name: "Pilsen Lager", tagline: "Unleash the Yeast Series.", first_brewed: "09/2013", description: "Our Unleash the Yeast series was an epic experimen…nols, although it can add a hint of butterscotch.", …}
4: {id: 5, name: "Avery Brown Dredge", tagline: "Bloggers' Imperial Pilsner.", first_brewed: "02/2011", description: "An Imperial Pilsner in collaboration with beer wri…hat rock our world, and the people who make them.", …}
5: {id: 6, name: "Electric India", tagline: "Vibrant Hoppy Saison.", first_brewed: "05/2013", description: "Re-brewed as a spring seasonal, this beer – which …re also added to produce a genuinely unique beer.", …}
6: {id: 7, name: "AB:12", tagline: "Imperial Black Belgian Ale.", first_brewed: "07/2012", description: "An Imperial Black Belgian Ale aged in old Invergor…yberries and blackberries beause they were local.", …}
7: {id: 8, name: "Fake Lager", tagline: "Bohemian Pilsner.", first_brewed: "03/2013", description: "Fake is the new black. Fake is where it is at. Fak…y faux masterpiece with added BrewDog bitterness.", …}
8: {id: 9, name: "AB:07", tagline: "Whisky Cask-Aged Scotch Ale.", first_brewed: "03/2010", description: "Whisky cask-aged imperial scotch ale. Beer perfect… beer capable of holding back the Scottish chill.", …}
9: {id: 10, name: "Bramling X", tagline: "Single Hop IPA Series - 2011.", first_brewed: "01/2011", description: "Good old Bramling Cross is elegant, refined, assur…apple and ginger jam my grandmother used to make.", …}
10: {id: 11, name: "Misspent Youth", tagline: "Milk & Honey Scotch Ale.", first_brewed: "04/2013", description: "The brainchild of our small batch brewer, George W…erously drinkable milk sugar- infused Scotch Ale.", …}
11: {id: 12, name: "Arcade Nation", tagline: "Seasonal Black IPA.", first_brewed: "12/2015", description: "Running the knife-edge between an India Pale Ale a…ryness from the malt bill at each and every turn.", …}
12: {id: 13, name: "Movember", tagline: "Moustache-Worthy Beer.", first_brewed: "11/2009", description: "A deliciously robust, black malted beer with a dec…rovides an enticing backdrop to the Cascade hops.", …}
13: {id: 14, name: "Alpha Dog", tagline: "Existential Red Ale.", first_brewed: "02/2010", description: "A fusion of caramel malt flavours and punchy New Z…hops. A session beer you can get your teeth into.", …}
14: {id: 15, name: "Mixtape 8", tagline: "An Epic Fusion Of Old Belgian, American New Wave, And Scotch Whisky.", first_brewed: "01/2012", description: "This recipe is for the Belgian Tripel base. A blen…, fruity esters, and punchy citrus hop character.", …}
15: {id: 16, name: "Libertine Porter", tagline: "Dry-Hopped Aggressive Porter.", first_brewed: "01/2012", description: "An avalanche of cross-continental hop varieties gi… toffee, bitter chocolate and hints of woodsmoke.", …}
16: {id: 17, name: "AB:06", tagline: "Imperial Black IPA.", first_brewed: "04/2011", description: "Our sixth Abstrakt, this imperial black IPA combin…our favourite American hops. Roasty and resinous.", …}
17: {id: 18, name: "Russian Doll – India Pale Ale", tagline: "Nesting Hop Bomb.", first_brewed: "08/2014", description: "The levels of hops vary throughout the range. We l… and yet still lends different characters to each", …}
18: {id: 19, name: "Hello My Name Is Mette-Marit", tagline: "Lingonberry Double IPA.", first_brewed: "06/2013", description: "We sent this beer to Norway where it was known as …nous bitter edge layered with dry berry tartness.", …}
19: {id: 20, name: "Rabiator", tagline: "Imperial Wheat Beer", first_brewed: "03/2011", description: "Imperial Wheat beer / Weizenbock brewed by a homes…nk banana bread, bubble gum and David Hasselhoff.", …}
20: {id: 21, name: "Vice Bier", tagline: "Hoppy Wheat Bier.", first_brewed: "04/2013", description: "Our take on the classic German Kristallweizen. A c… balanced with the American and New Zealand hops.", …}
21: {id: 22, name: "Devine Rebel (w/ Mikkeller)", tagline: "Oak-aged Barley Wine.", first_brewed: "12/2008", description: "Two of Europe's most experimental, boundary-pushin… and was going to be partially aged in oak casks.", …}
22: {id: 23, name: "Storm", tagline: "Islay Whisky Aged IPA.", first_brewed: "12/2007", description: "Dark and powerful Islay magic infuses this tropica…to the peated smoke imported directly from Islay.", …}
23: {id: 24, name: "The End Of History", tagline: "The World's Strongest Beer.", first_brewed: "06/2011", description: "The End of History: The name derives from the famo…caramel and cloves are intensified by boozy heat.", …}
24: {id: 25, name: "Bad Pixie", tagline: "Spiced Wheat Beer.", first_brewed: "10/2008", description: "2008 Prototype beer, a 4.7% wheat ale with crushed juniper berries and citrus peel.", …}
length: 25
__proto__: Array(0)
Enter fullscreen mode Exit fullscreen mode

Get excited cuz now you can work with this data!

fetch('https://api.punkapi.com/v2/beers')
  .then(response => response.json())
  .then(beers => console.log(beers[5].name));
Enter fullscreen mode Exit fullscreen mode

What beer does this return?

5: {id: 6, name: "Electric India", tagline: "Vibrant Hoppy Saison.", first_brewed: "05/2
Enter fullscreen mode Exit fullscreen mode

Let's talk about that second optional argument. We could request to do a few things here with the API

POST - is requesting to add data

PATCH - is requesting to edit the data

DELETE - is requesting to delete some data

the second argument will be a JavaScript object which will have information that will communicate to the backend and the application. One way to set a POST is like this. The reqObj will have three key-value pairs.

let reqObj = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
},

  body: JSON.stringify({
    name:,
    tagline:

})
};

fetch('https://api.punkapi.com/v2/beers, reqObj)
.then(resp => resp.json())
.then(beer => {
console.log(beer)
Enter fullscreen mode Exit fullscreen mode

Let's break down those key-value pairs.
method: 'POST' - this is the request we are sending to the backend.
headers:
Content-Type is the type of data content we are sending
Accept is the data content we will take in return
body: is data this is in string format.

The way we would set up Patch is like this

fetch(`https://api.punkapi.com/v2/beers/${beerId}`,{
  method: 'PATCH',
  headers: {
   'Content-Type':'application/json'
},
  body: JSON.stringify({
   "new updates"
})
})
.then(resp => resp.json())
.then(beer => {
console.log(beer)
})
Enter fullscreen mode Exit fullscreen mode

NOTICE we used bac-tics with this fetch. We want to edit individual beers and to do that we need to specifically use the beerId. So we interpolate the beeId into the URL.

Now with deleting a beer it's much less code. We still need the beerId and we only need the method. like this

fetch(`'https://api.punkapi.com/v2/beers/${beerId}`,{ 
  method: 'DELETE' 
})
.then(resp => resp.json())
.then(beer => {
console.log(beer)
})
Enter fullscreen mode Exit fullscreen mode

Alt Text

I hope this was helpful and to look at some free API's check out https://github.com/public-apis/public-apis

Top comments (0)