# Fetch API
Getting data from an API or from a database is a four-step action.
- Calling the
fetch()
methode to starts a request - The
fetch()
methode returns a promise - When the request completes, the promise resolves a response object
- This response returns a lot of information, but the actual data can be extracted in JSON format (with
response.json()
) or in raw text (withresponse.text()
)
The response of the fetch()
method will pass through the chain (one or more) of .then()
handlers to process the data and a .catch()
handler to process the errors: fetch().then().then().then().catch();
IMPORTANT
Every .then()
handler MUST return something so it can be used as input data for the next .then()
handler.
With the fetch()
method, the first .then()
handler must always return response.json()
(if the response is in JSON format) or response.text()
(if the response is just raw text)
fetch()
can handle all the different HTTP verb methods (opens new window) you can expect from a CRUD (Create, Read, Update and
Delete)
verb (method) | action | description |
---|---|---|
GET | read | get date from an API, database, ... |
POST | create | post date to an API, add data to a database, ... |
PATCH/PUT | update | update a record in the database, ... (not used in this course) |
DELETE | delete | delete a record from the database, ...(not used in this course) |
The fetch(url, options)
method accept two parameters:
url
: the URL to fetch fromoptions
: some optional parameters
A full description of all options can be found here (opens new window)
The ones you will use the most are:
option | possible values |
---|---|
method | GET (default), POST , PUT , DELETE , ... |
headers | 'Content-Type': 'application/json' , ... |
body | JSON.stringify(data) , ...( data type must match Content-Type header) |
# Basic HTTP verbs
To demonstrate a very basic example of the different verbs, we use the fake APIs. The actions are not actually taking place, but the response 'fakes' this is really happens.
# GET
Use the get
method to retrieve data from an API or from a database. You don't have to explicitly set this method, because this is the default method when for fetch()
.
To retrieve information with fetch()
, you only have to pass the URL as a parameter
This example gets all the users on page 2 with this URL: https://reqres.in/api/users?page=2 (opens new window). We are only interested in the key data
which contains an array of six users.
See the Pen FSGet by Jitse Beyens (@BeyensJ) on CodePen.
# POST
We use the POST
method to send new data to an API or insert something in a database. The data that will be sent to the API and the method(POST
) are passed to the options
parameters of the fetch()
method
See the Pen FSPost by Jitse Beyens (@BeyensJ) on CodePen.
# Error handling
The fetch()
promise will reject (trow an error that will be handled bij thecatch()
) handler ONLY if:
- a network error occurs
- a CORS (opens new window) header is sent by the server
- the base URL don't exists
In every other situation e.g: faulty parameters on the URL, access not allowed, etc... the fetch()
promise will resolve, and you have to deal with these kind of errors yourself. This can be easily done within the first then()
handler, just before returning response.json()
.
When we look at the response object (opens new window), there are tree properties we can use to test the status of the response (look at the result tab on the GET
example)
property | description |
---|---|
status | status code (opens new window) e.g: 200 (ok), 404 (not found), 403 (forbidden), ... |
ok | true if status code is in the range of 2xx otherwise false |
statusText | which corresponds to the HTTP status code (but most of the time this string is empty) |
Now you can trow an error if response.ok
is false
, else sent the data (response.json()
or response.text()
) to the next then()
handler.
Some possible scenarios to respond to an error:
See the Pen Untitled by Jitse Beyens (@jitse-beyens) on CodePen.
This time we use jsonplaceholder (opens new window), another frequently uses fake API.
Open the console and look what's inside response.ok
, response.status
and the error message
See the Pen FSMoreFetchErrors by Jitse Beyens (@jitse-beyens) on CodePen.
# Preloader
Fetching data from an API sometimes takes a few seconds so it's always a good idea to show your visitors some kind visual information that something is happening in the background. This can be in the form of a preloader, a spinner or a simple text message. You want to show the preloader just before fetching the data and hide the preloader when the data is rendered to the page or when an error occurred.
See the Pen FSFetchPreLoader by Jitse Beyens (@jitse-beyens) on CodePen.