Fetch API Introduction

Sharing buttons:


hey guys what's going on

so a few days ago I created an AJAX

crash course where we looked at Ajax and

xhr the XML HTTP object which is used to

make asynchronous calls from your

browser to a server and you know get

data asynchronously and so on now there

was a comment from someone that had

mentioned that they think that xhr is

outdated so I don't personally agree

with that I don't think that that those

terms outdated deprecated should be

thrown around and the reason for that is

because when someone is learning

JavaScript like let's say right now

someone wants to learn JavaScript they

have to learn about xhr and Ajax they

can't just go right to the fetch API you

know because they're gonna run into this

at least for the next ten years you have

new standards like fetch that aren't

even fully compatible a lot of the

different parts aren't even fully

compatible with every browser so these

are very new technologies so you can't

just you can't just throw away the old

ones okay especially when they're very

reliable they've been used for a while

and they're used in you know millions

and millions of applications so I don't

agree with that but I do agree that you

should learn newer standards okay I

believe that you should learn the older

ones you know get wrap your head around

that and then move on to things like

fetch just like with JavaScript I

believe you should learn es5 first and

then move on to es6 because you're gonna

run into it but enough of that what

we're gonna do is we're gonna focus on

fetch today we're gonna build this

sandbox thing here I actually added some

bootstrap styles and made it look nice

we're not gonna do that till the end

because I want to focus on the API first

and then we'll just you know for fun

we'll make it look nice but basically

we're gonna do kind of the same stuff

that we did within the Ajax crash course

where we fetch data from a text file

asynchronously we fetched from a local

JSON file we also fetch from an external

API okay we use the github API in the

Ajax video we're going to use the JSON

placeholder API in this video

which allows you to make all kinds of

requests so basically this button here

if I click it it's going to get the text

asynchronously from a text file this one

will get JSON and get all the users and

display them in the browser and then

this one will actually fetch from the

Jason placeholder and it'll get a

hundred posts with titles and bodies and

we'll put that in the browser

alright we're also going to make a post

request to the API you'll see if I say

test actually let me open up my console

so if I say test and then test test body

and we submit that will actually make a

post request using fetch and it'll give

us a response you'll see the ID is 101

initially it's a hundred different posts

so I the ID being 101 shows you that

we've basically added a new post okay it

doesn't physically get added to their

database but it does you know make a

successful response so that's what we'll

be building we're also gonna learn a

little bit about some new es6

technologies like arrow functions and

template strings you can see we're using

a template string here which is much

easier than doing the old concatenation

which is what we did in the Ajax course

but like I said you should know both

ways okay so yeah that's what we'll be

doing guys hopefully you enjoy it and

let's go ahead and jump into it hey guys

I've just created a new discord server

that's open to the public the goal is to

have a place where people can go to help

each other out for programming issues as

well as just a place to discuss new

ideas and get feedback I also check in

daily there's a channel to request

videos on YouTube and much more so if

you want to check it out just go to

discord GG slash traversing media

alright guys so we're gonna get started

here I'm using Visual Studio code I'm

also using the live server extension if

you want that you can click on the

little extension icon search for a live

server and just go ahead and install

that okay if you're using atom atom live

server is another good option if you're

using xampp just any any kind of server

you need to use okay what else npm has a

bunch of them npm install - g live -

server will give you

a nice little one a nice little autoload

server as well so I have a folder here

called fetch sandbox I'm gonna create an

index.html file alright and we're just

gonna put some basic head body tags

stuff I use Emmet so I did exclamation

tab if you want to use Emmet on another

editor like Adam or sublime text you'll

have to install it as a plugin so for

the title let's say fetch API sandbox

and we're going to actually its first of

all just add a button in here so we'll

say button we'll give it an ID of get

text and let's say get text alright now

to run this on live server I'm just

going to right click and say open with

live server and that's gonna open it up

in our browser alright so we have our

button now let's go ahead and put some

script tags down here and we need to add

an event listener so we'll say document

dot get element by ID as the idea of get

text and then we just want to add an

event listener what so add event

listener the event we want to listen to

is a click and then we want to run a

function called get text all right so

let's create that function get text and

let's just do a console dot log and

we'll just log let's just log one two


all right so we'll reload let's make

sure Chrome tools is open with the

console click the button and we get one

two three all right so what we want to

do is we want to fetch a text file okay

asynchronously so let's create a new

file over here and I'm just going to

call it sample dot txt and inside here

I'm just gonna say I am a sample text

file and save and we can close that up

okay so we're gonna call the fetch

function here whoops and then it's going

to take in a parameter which is going to

be either a URL or a file name whatever

it is you're trying to get

our case is sample dot text now fetch

returns a promise so what that means is

it's kind of like a placeholder for the

response that we're gonna get

asynchronously so to work with promises

we need to use dot then okay make sure

you don't have a semicolon right here

it just goes dot then if you want to put

this on the same line like that you can

do that as well but I like to put it on

a separate line so this then is going to

take in a function and then what's

passed in here res or response whatever

you want to use and we're gonna console

dot log that res that response

okay so let's save that and click the

button and it gives us a response with

some stuff here gives us the status you

can see 200 if you watch the Ajax crash

course you know 200 is the status that

we want that means that everything went

okay I've found the file or the URL

gives us status text of okay gives us

the URL of the file so just a basic

response now what we want to do is we

want to get the text okay now there's

different I guess functions you could

call them so for instance if we say dot

text like that okay that's going to give

us the response of the promise with the

text you can see right here promise

value is I am sample text file whatever

is in that file if this was Jason then

we would want to do res dot Jason okay

now I want to get the actual text not

just this promise status and value so

what we need to do is return this res

dot text right here and not just log it

so we'll get rid of the console.log and

then we'll just say return all right and

then we need to add another dot then

okay so dot then and we're going to put

a function in here and then this is

going to give us our data so we can pass

in data and then

we can console dot log data okay we'll

save it and then we click the button and

now we're getting the actual text that's

in the file all right so this this is

cleaner than you know a standard xhr

Ajax request but we can make it look a

little better if you want to use arrow

functions so what I'm gonna do just to

show you the difference is comment this

out and then we'll do fetch sample

sample dot txt and same thing we're

gonna do dot then except we're just

going to take the response and we're

going to use an arrow right here and

we're gonna say we want that to res dot

text like that and then we'll do our

second dot then and in here we'll take

the data and use an arrow function and

say console dot log data that semicolon

shouldn't be there so let's save that

and click the button and we get the same

result so this looks much cleaner than

this okay but it's up to you what you

want to do now if you want to do

something else with the data aside from

just logging it with this one line then

you're gonna have to set it to a code

block or to a set of curly braces all

right and what I want to do is insert it

into the Dom into the web page so I'm

gonna put a div up here with an ID of

output and then in here what we'll do is

we'll say document dot get element by D

output and let's set that equal to the

data okay so now we'll save that click

the button what did I do

oh nice forgot to do inner HTML

there we go so now we're taking that

that data that's being fetched and we're

putting it into into the browser all

right so that's a simple text file oh

one more thing if you want to catch

errors with these promises you can

actually add on dot catch and pass in

error actually what we'll do is say

error and set it to an arrow and then

just console dot log error all right so

now let's do a JSON file so I'm gonna

create a new file called users dot Jason

so I bought those freaking seagulls out

there and I'm gonna grab I'm just gonna

copy this so this is the same JSON file

we used in the Ajax crash course it's

just a couple users couple of walking

dead users and what we'll do is copy

actually let's create a new button

so we'll do button we'll give it an ID

of let's say get users all right

so we'll create another event listener

and this will be get users it's going to

call a function called get users let's

create that function down here okay

actually I need to put in the word

function all right so let's see forget

users pretty much doing the same thing

so we're gonna say fetch users dot jason

and we want to do i keep spelling fetch

wrong so fetch users dot jason then we

want to do our dot then and we're gonna

take the response and this time instead

of setting it to res dot txt we're gonna

do res dot jason like that alright and

then we need our second dot then and in

here actually i'm not going to use that

semicolon in here we're gonna get our

data set an arrow function to a code

block and let's go ahead and get ready

to put this output into the browser so

we're gonna set a variable called output

notice i'm using let i'm going to be

using he has six standards in this video

so we'll say let output equals and let's

just make this an h2 to begin with so

we'll say h2 users and then what i'm

gonna do is i'm going to loop through

our result actually you know what let's

console.log our result first just so you

can see that it actually works so we'll

console.log data

let's click get users and there's our

three users okay so we're going to look

through these and i'm gonna do it a

little different than I did in the Ajax

course we're gonna use the dot for each

okay so we can do this with arrays dot

for each and then pass in a function and

then we need an identifier so let's

let's say user all right and then for

each iteration we want to add on to that

output variable so we want to add on or

a pen

and we do that with a plus equals okay

now I'm also going to use template

strings here so we want to use backticks

not single quotes these are backticks

these are to the left of your number one

key so with with template strings we

don't have we can just have multiple

lines we don't have to you know

concatenate with quotes and plus signs

and all that we can just simply put in

some HTML here so let's go ahead and put

a ul will close that ul and we'll put in

some hell I tags and in here let's get

the ID now if you want to insert a

variable which we want from this user

right here because it's looping through

and then we can access each user with

this so to put a variable in here you

need to use money sign and then curly

braces see how it changes color and then

we can say user dot ID okay we can

access any of these values ID email or

name okay so we're gonna get the ID

we're also going to get the name so

that'll be user dot name and then we're

going to get the email so that'll be

user dot email all right so that's gonna

get all that stuff in that output

variable then we want to go outside of

the loop and we want to grab let's say

document dot get element by ID we want

the output element and we want to say

dot inner HTML and set that to that

output variable and save get users and

there we go okay so this is a much nicer

way of doing it then we did in the Ajax

crash course okay but again this isn't

these are newer standards you know so in

my opinion you need to know both ways

all right so let's see what else we want

to do here now let's fetch data from an

outside API so we're gonna use this JSON

placeholder and you can fetch post

comments albums photos to do's and users

we're gonna grab some posts

click that you'll see they'll give us a

hundred posts if we go all the way down

here you'll see the last one has an idea

of 100 so what we want to do is create

another button I'm just going to see

I'll just copy this so for this one

we'll say actually I'm gonna change this

text to get Jason and this one will be

get API data all right and then we'll

change this button ID to get posts and

then we want another event listener you

can see the pattern here so get posts

and we're gonna call a function called

get posts alright let's go down here and

let's actually copy get users cuz it's

pretty similar so we'll change this to

get posts and instead of fetching you

know a local file we're gonna grab this

URL right here so we'll copy that paste

that in okay we it is Jason so we want

to keep this line let's see we also want

for let's see the output right here

let's change this to posts and then in

the output if we look at what we have

available we have an ID we have a title

and a body so let's use those but

instead of using a UL here what I'm

gonna do is I'm gonna put in a div and

later on we're gonna add some bootstrap

classes to these but we'll have a div

and then we'll do an H let's do an h2 so

what I did h2 now h3 and this is where

the title will go so we can use these

variables we can say let's use post here

because we're not working we're not the

data is not users anymore it's posts so

we'll change that to post and we'll say

post dot title

all right and then we'll put in a

paragraph and we'll say post dot body

all right and we'll put it in the output

so let's save let's go back and click

that and you'll see we get all of those


all right so pretty easy so now what I'm

gonna do is create a form so we can make

an actual post request to the API so

let's see we're gonna put the form let's

see actually know what I want to do is

put an HR right here above the the

output and under the output will put our

form okay so the form is gonna have an

ID of add post okay and let's see inside

the form let's put a div and inside here

we're going to have an input

let's do input type text and we need to

give it an ID of title let's also give

it a placeholder of title and then we'll

copy that div will add the bootstrap

stuff later don't worry this is going to

be body actually this is gonna be a text

area so I'm going to change this okay

let's change the placeholder to body all

right and then we just need an input

of submit and give it a value of submits

alright so there's our form let's save

it looks horrible but that's fine now we

need to add an event listener here now

this is going to be an event listener

for our forum let's go ahead and copy

this okay so remember the forum has an

ID of add post so we wanted to add an

event listener except this time it's

going to be a submit and we want to call

add post okay that's the function we

want so let's go down to the bottom here

and create a function called add post

okay now since it's a forum we're gonna

pass in an event parameter we're gonna

say e dot prevent default which is going

to stop it from actually submitting to a

file alright now what we want to do here

is we want to get the values of the

title and the body fields so let's

create some variables we'll say let

title equals document dot get element by

D gave it an ID of title and we want to

get the value okay let's do the same

thing for the body

I'll change this right here to body and

then what we're gonna do is we're gonna

call fetch okay now inside here we're

gonna put our URL which is gonna be it's

gonna be the same URL is this that we

made the get request to because if you

look at the the routes for this API you

can make a post request to slash posts

okay just like you can make a get

request to slash posts so we'll go ahead

and paste that in alright now this is

actually going to take a second

parameter which is going to be an object

with with some stuff here so we want to

add in a method we want to let it know

that this is a post method okay we also

want to add in some headers all right so

for headers this is actually going to be

an object and we're gonna say accept

so for accept we want Jason so

application slash Jason and also let's

say text slash plain and let's say

anything slash anything and then we also

want to apply the content type okay so

content type is going to be application

Jason there should be a comma there

alright so those are the headers that we

need and then we need a body

okay so body is going to be where we

apply the data now we have our variables

here but it needs to be inside it needs

to be jason so it needs to be inside of

curly braces and then we're going to say


I'll say title title body body now we

just want to wrap this in a function

called Jason dot stringify okay which

will actually convert it to a string

before it's sent okay and then we just

need to go down here and just like we

did with all the other requests we need

to do a dot then we're gonna set res to

res dot Jason and then we're gonna do

dot then and we're gonna say data and

then we can do whatever we want with the

respondent the data that is responded

we're just gonna log it okay and the

response it gives you is the actual post

that you're adding okay all right so

let's see I think that that should do it

so that's a standard post request using

fetch so let's save let's go over here

and reload for good luck and let's say

title test body test body and submit and

there we go so that's our response you

can see it has an ID of 101 okay it's

not gonna get added to right here you're

not gonna see it on their site it's not

going to persist to the database but you

see it ends this ends at 100 so ours is

101 okay it just doesn't get persisted

so that's it as far as making our

requests um now there's there's more to

with the fetch API but I'm not gonna get

too deep into it this is just an

introductory now what I want to do is

just make this look a little better with

some bootstrap just for fun so let's go

to get bootstrap calm and we'll grab

we'll go to get started we'll grab just

the CDN for the CSS so this link right

here and we'll put that up in our

head area and let's see what are we

gonna do here as far as classes

let's wrap everything in a container by

the way if you're interested in

bootstrap for I do have a udemy course

on it called bootstrap for from scratch

with five projects let's see we're gonna

end the Dib right here so that wraps

everything in a container all right and

then let's see we're gonna wrap it's put

an h1 right here first of all let's give

this h1 a class of display - for I'm

also going to give it a class of MB 4

which is margin-bottom 4 just to push

things down and then we'll say fetch

fetch API sandbox alright and then all

these buttons here I'm going to wrap in

a div and I'm going to give this div a

class of D flex so we can use flexbox

and that'll just align everything and

then for each button let's give these

some classes so say BTN BTN secondary

secondary let's also do mr four which is

margin right four just to push the next

button over so go ahead and copy that

class paste it in here let's change it

to success make it green okay this

button here paste it in and we'll change

this one to yellow

alright let's see what that looks like

alright cool

actually the first one I wanted primary

not secondary I want that to be blue

alright so that's that now for the form

which looks horrendous let's add to

these divs right here a class of form

group and we'll add to these inputs a

class of form control ok and the submit

let's add a class of BTN and BTN

secondary and save and there we go now

for the responses let's go down here for

the get jason these users right here I'm

just going to make this ul a list group

give it a class of list group and then

these lis will give a class of list

group item I'll just copy that okay save

that there we go so that looks better

let's also give the d UL a class of

margin bottom three that way they're not

right on top of each other all right so

let's see what else we got here

for the API data let's go down there and

we're just going to give this div a

class of card and card body save that

and also let's do MB 3 oops what


card there we go

and I think that's pretty much it oh

let's give this post this Sh to right

here we'll give that a class of mb mb

for cool i'll do it to the users h2 as

well and that's it

so now we have our fetch API sandbox now

if you guys want to read more about

fetch and maybe look into doing put

requests and things like that delete

requests maybe use some different api's

if you want there's some really good

public API is out there or maybe even

create your own maybe use you know

create an express mongoose api or

something some kind of restful interface

but that's gonna be it for now guys

hopefully you enjoyed this and you

learned a little something about fetch

and maybe a little something about es6

so that's it and I will see you in the

next video