Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
      You have completed Working with the Fetch API!
      
    
You have completed Working with the Fetch API!
Preview
    
      
  Let's get started by writing a basic fetch request using the global fetch() method. Then we'll use JavaScript promises to handle the results returned from the server.
Code Snippets
fetch('https://dog.ceo/api/breeds/image/random')
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
                      To code along with me, launch
the workspace with this video or download
                      0:00
                    
                    
                      the project files for this workshop and
open them in your favorite text editor.
                      0:03
                    
                    
                      When you open the project files or
                      0:07
                    
                    
                      workspace, you should see
an index.html file and a js
                      0:08
                    
                    
                      folder containing a file named app.js,
the two main files we'll be working with.
                      0:13
                    
                    
                      When you preview index.html in the browser
you'll see an empty select menu and
                      0:18
                    
                    
                      div container, and
below them a simple form.
                      0:24
                    
                    
                      Over in app.js,
there are three pre-written variables.
                      0:27
                    
                    
                      It's selecting elements from index.html
like the select menu, card div and form.
                      0:32
                    
                    
                      We're going to be working with these
elements throughout the workshop.
                      0:39
                    
                    
                      So the fetch API provides an easier way to
make network requests in the browser and
                      0:42
                    
                    
                      handle responses.
                      0:48
                    
                    
                      To make a request,
you use the global fetch method.
                      0:49
                    
                    
                      Fetch takes one mandatory argument.
                      0:52
                    
                    
                      The path to the resource
you want to fetch.
                      0:55
                    
                    
                      I'm going to request data from
the Dog API at dog.ceo/dog-api.
                      0:58
                    
                    
                      This simple API returns
a list of dog breeds and
                      1:03
                    
                    
                      random images of dogs either by breed or
all breeds.
                      1:07
                    
                    
                      Now many APIs require an API key to let
you connect to their web server and
                      1:11
                    
                    
                      access data.
                      1:16
                    
                    
                      To keep things simple I chose a public
API that does not require an API key.
                      1:17
                    
                    
                      And here you can see all the different
endpoints like all dogs by breed,
                      1:22
                    
                    
                      by sub breed and so on.
                      1:26
                    
                    
                      So first, I'm going to return
data from the All dogs endpoint.
                      1:28
                    
                    
                      And I want this endpoint that returns
a random dog image from all the breeds.
                      1:33
                    
                    
                      So I can click this JSON link and
copy this URL in the address bar.
                      1:39
                    
                    
                      Over in app.js under
the fetch functions comment,
                      1:46
                    
                    
                      I'll first type the fetch method, and
pass it the URL to fetch as a string.
                      1:50
                    
                    
                      As I mentioned in the previous video,
Fetch API uses JavaScript promises to
                      2:01
                    
                    
                      handle the results
returned from the server.
                      2:05
                    
                    
                      Again, be sure to watch our workshop on
JavaScript promises if you're not sure how
                      2:08
                    
                    
                      promises work.
                      2:12
                    
                    
                      A promise represents the eventual
result of an asynchronous operation.
                      2:13
                    
                    
                      Similar to callbacks, promises allow
us to wait on certain code to finish
                      2:18
                    
                    
                      execution before running the next bit of
code in a cleaner, more readable way.
                      2:22
                    
                    
                      Now the fetch method
itself returns a promise.
                      2:27
                    
                    
                      So for example, if I copy this fetch
method and run it in my browser's console.
                      2:31
                    
                    
                      Notice how it returns a promise object.
                      2:39
                    
                    
                      And if I click the arrow to expand it, we
see that the promise status is resolved.
                      2:42
                    
                    
                      That means the asynchronous task
was completed successfully.
                      2:49
                    
                    
                      The promise was fulfilled because
the browser received a response from
                      2:52
                    
                    
                      the server.
                      2:55
                    
                    
                      Now nothing's happened yet
in our app because we haven't written
                      2:56
                    
                    
                      any code to handle the response and
the return data.
                      2:59
                    
                    
                      We'll do that now using
a sequence of promises.
                      3:03
                    
                    
                      Promises get executed in sequence.
                      3:06
                    
                    
                      You chain then methods to the fetch method
which returns a promise of their own.
                      3:08
                    
                    
                      The methods get executed sequentially
once the previous promise is fulfilled.
                      3:13
                    
                    
                      In other words, something happens
after something else is resolved.
                      3:18
                    
                    
                      So in our case,
the fetch promise is fulfilled or
                      3:23
                    
                    
                      resolved when the browser receives
the response from the server.
                      3:26
                    
                    
                      So, next I'll chain a then
method to fetch and
                      3:30
                    
                    
                      pass it a function using an error
function that takes the response via
                      3:33
                    
                    
                      a parameter I'll call response and
logs it to the console for now.
                      3:39
                    
                    
                      Remember you're able to place the chain
then methods on separate lines to make
                      3:49
                    
                    
                      your code easier to read.
                      3:53
                    
                    
                      Now, this isn't immediately going
to return the data we expect.
                      3:55
                    
                    
                      You see once the data finishes loading and
a fetch promise is fulfilled,
                      4:00
                    
                    
                      fetch returns a response object containing
information about the response,
                      4:05
                    
                    
                      like the status code and
the corresponding status message.
                      4:10
                    
                    
                      So here, the response lets us know
that the request went through.
                      4:15
                    
                    
                      The actual data we want is in the body
property of the response object.
                      4:19
                    
                    
                      Now the API we're using
returns data in JSON.
                      4:24
                    
                    
                      So in order to access and use the data,
we need to parse it to JSON first.
                      4:28
                    
                    
                      So I'll change the function
to return the raw data
                      4:33
                    
                    
                      in the response in JSON
format using response.json.
                      4:39
                    
                    
                      There are different methods you
can use on a response object.
                      4:45
                    
                    
                      Each lets you handle different
response types, for example,
                      4:48
                    
                    
                      blob for images, text for
text files and more.
                      4:52
                    
                    
                      I posted examples of some of the other
common methods in the teacher's notes.
                      4:56
                    
                    
                      So, response.json reads the response and
returns a promise that resolves to json.
                      5:01
                    
                    
                      And because we're using
a single line arrow function,
                      5:08
                    
                    
                      the promise returned from
the response.json() method call
                      5:12
                    
                    
                      will be implicitly returned
from our arrow function.
                      5:15
                    
                    
                      And this allows us to chain another
                      5:19
                    
                    
                      then method() onto our
existing then() method call.
                      5:22
                    
                    
                      So inside this method is where we
can do something with the json data.
                      5:25
                    
                    
                      For example, iterate over it, and
insert it into our page's content.
                      5:30
                    
                    
                      So in the second then method, I'll pass
a function that takes the json data,
                      5:34
                    
                    
                      via a parameter I'll call data, and
logs it to the console for now.
                      5:40
                    
                    
                      Let's go back to our console, refresh.
                      5:48
                    
                    
                      And great,
now we're getting the actual JSON data.
                      5:51
                    
                    
                      In the JSON object there's
a property named message, and
                      5:55
                    
                    
                      the value is the URL to an image.
                      5:59
                    
                    
                      So to access the value of
message I'll log data.message.
                      6:01
                    
                    
                      Refresh the page, and this is exactly
what we need, the URL as a string.
                      6:12
                    
                    
                      And just like that with three short and
simple methods, we have our data.
                      6:18
                    
                    
                      Now, as you can see,
                      6:24
                    
                    
                      each time I refresh the page,
the endpoint returns a different URL.
                      6:25
                    
                    
                      And now, we can use this URL in an image
element source attribute to display
                      6:30
                    
                    
                      a random dog image.
                      6:34
                    
                    
                      And we'll do just that in the next video.
                      6:35
                    
                    
                      Keep in mind that by default,
fetch won't send or
                      6:38
                    
                    
                      receive any cookies from the server.
                      6:41
                    
                    
                      And this will affect you in dealing
with the user authentication.
                      6:43
                    
                    
                      So the fetch method also accepts
an optional second parameter,
                      6:47
                    
                    
                      an init options object you can use
to customize the HTTP request.
                      6:51
                    
                    
                      So for example you can send a request
with credentials included, or
                      6:56
                    
                    
                      make a post request instead
of the default get request.
                      7:00
                    
                    
                      And you'll learn more about this in the
final video when we post data to a server
                      7:04
                    
                    
                      using fetch.
                      7:08
                    
                    
                      For now you can read more about it in
the teacher's notes with this video.
                      7:09
                    
              
        You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up