JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  • What is Fetch?
  • Basic Fetch Components
  • Benefits of Fetch
  • Http-Server
  1. 03-API Fundamentals
  2. 3-Fetch

Fetch Intro

What is Fetch?

Fetch in programming means pretty much the same as playing fetch with your dog. The Fetch API allows us to "fetch" or pull resources from across the web: text files, code, data, and more.

Fetch centers around one concept for the most part: a generic definition of objects known as Request and Response. Because these objects are generic, they can be used anywhere you need them.

Let's first go through the basic model of a fetch 1. The fetch() method takes in your desired resource's path as a mandatory argument. 2. The Request object returns a Promise that resolves to the argument's Response. 3. After retrieving a Response, a multitude of methods define the body content and how it will be handled. 4. Please note that you can use the Request() and Response() constructors to directly create requests and responses, but they are more likely to be created by other API actions.

Basic Fetch Components

  • GlobalFetch - contains the fetch() used to fetch a resource.

  • Headers - HTTP response/request headers can be queried and allow you to do things such as retrieving, updating, or deleting.

  • Request - a resource request. It contains the method of the request (GET, POST, etc.), the url, associated headers, and more.

  • Response - the response to the request. It contains the headers and url, but more importantly replies with the status code to determine whether or not the request was successful.

  • Body - contains methods relating to the main content of the response/request that allow you to specify content type and how to handle it.

We'll go through an in-depth example or two later, but here's a basic example of a fetch request.

fetch('http://example.com/movies.json')
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        console.log(myJson)
    })

Let's talk about what fetch components this has:

  • http://example.com/movies.json is the argument, the path of our desired resource.

  • The response object, which will return some JSON.

  • However, this is only an HTTP response. The json() method is required to extract the JSON.

Benefits of Fetch

  • In general, Fetch is simpler than the previous standard of XHR (XMLHttpRequest).

  • Fetch is promise-based, which allows us to write cleaner code.

  • Fetch has a "neat" definition for requests/responses. You can write a function to modify a request before it is sent.

  • Not necessarily a benefit, but Fetch doesn't send cookies. Authentication must be handled manually.

Http-Server

In order to access some APIs without deploying an application, you can create a virtual server on your machine to accept the returned data using an npm package called http-server. Run the following command in your terminal window: WINDOWS npm install -g http-server MAC sudo npm install -g http-server (The sudo command is sometimes, but not always, necessary to install npm packages globally. It requires administrator privileges for whatever console command follows it. It can lead to some very bad unintended consequences, however, so always try to install WITHOUT the sudo command first.) This will install the package globally so its accessible from any location. Once it's installed, just type http-server into your terminal. You should see something like the following appear:

Go to localhost:8080 and the app you're running should appear. If for some reason you get an error message saying that port 8080 is in use (or something along those lines), just add -p to specify a port number. A port number can be just about anything, but some of the more commonly used ones are 80, 3000, 4000, and 8080.

Previous3-FetchNextStar Wars

Last updated 7 years ago

http-server