HTTP Requests
Creating calls to various APIs using 4 techniques
Summary:
JavaScript is the language of the web because of its asynchronous capabilities. AJAX, which stands for Asynchronous JavaScript and XML, is a set of tools that are used together to take advantage of JavaScript’s asynchronous capabilities.
There are many HTTP request methods, two of which are GET and POST.
GET requests only request information from other sources.
POST methods can introduce new information to other sources in addition to requesting it.
GET requests can be written using an XMLHttpRequest object and vanilla JavaScript.
POST requests can also be written using an XMLHttpRequest object and vanilla JavaScript.
Writing GET and POST requests with XHR objects and vanilla JavaScript requires constructing the XHR object using
new
, setting theresponseType
, creating a function that will handle the response object, and opening and sending the request.To add a query string to a URL endpoint you can use
?
and include a parameter.To provide additional parameters, use
&
and then include a key-value pair, joined by=
.Determining how to correctly write the requests and how to properly implement them requires carefully reading the documentation of the API with which you’re working.
Four HTTP Requests
The four most commonly used types of HTTP requests are GET, POST, PUT, and DELETE.
GET : retrieving info from a website
POST : posting info to the source
Perform GET and POST requests using JavaScript's XHR object :
Datamuse API for GET requests
Rebrandly URL shortener API for POST requests
GET Requests : Asynchronous JavaScript & XML (AJAX)
enables requests to be made after initial page load
How to create an XHR GET request:
# XHR GET Requests
This section we create the boiler plate code for an AJAX GET request using an XMLHttpRequest Object:
# Using AJAX GET request to Datamuse API to search for words that rhyme
In this exercise, we will create a request to set a topic and find adjectives that describe the input word using query strings.
A query string contains additional information to be sent with a request. The Datamuse API allows us to retrieve more specific data with query strings attached to the request URL.
A query string is separated from the URL using a ?
character. After ?
, you can then create a parameter which is a key value pair joined by a =
. Examine the example below:
If you want to add an additional parameter you will have to use the &
character to separate your parameters. Like so:
XHR POST Requests
The major difference between a GET request and POST request is that a POST request requires additional information to be sent through the request. This additional information is sent in the body of the post request.
# Standard Boiler plate code for POST Requests
# Using Rebrandly API to shorten long URLs
Combining Promises to AJAX
This section we learn to use fetch()
, which uses promises to handle requests. Then, we will simplify requests using async
and await
.
We’ll use the Datamuse API for GET requests and Rebrandly URL Shortener API for POST requests.
# fetch() to GET request
Sample:
Inside of the
response
callback function, check theok
property ofresponse
inside of a conditional statement. In the code block of the conditional statement, returnresponse.json().
The reason we’re testing the
ok
property of the response object is that it will be a Boolean value. If there were no errorsresponse.ok
will betrue
and then your code will returnresponse.json()
.Add a second argument to
.then()
, it will be an arrow function that will handle our failures. Separate the first callback function from the second with a comma. The second callback function takes a single parameter,networkError
.In the code block of the second callback function, log
networkError.message
to the console.If we could not reach the endpoint at all, e.g., the server is down, then we would get this
networkError
.Chain another
.then()
method to the end of the first.then()
method.Pass the new
.then()
method a callback function that takesjsonResponse
as its parameter and returnjsonResponse
.The second
.then()
‘s success callback won’t run until the previous.then()
method has finished running. It will also not run if there was an error was thrown previously.
The fetch()
function:
Creates a request object that contains relevant information that an API needs.
Sends that request object to the API endpoint provided.
Returns a promise that ultimately resolves to a response object, which contains the status of the promise with information the API sent back.
Extension of the datamuse API project:
# fetch() POST Requests
Notice that the initial call takes two arguments: an endpoint and an object that contains information needed for the POST request. The rest of the request is identical to the GET request.
Async GET Requests
we’re going to take what you’ve learned about chaining Promises and make it simpler using functionality introduced in ES8: async
and await
.
Review
Using an
async
function that will return a promise.await
can only be used in anasync
function.await
allows a program to run while waiting for a promise to resolve.In a
try...catch
statement, code in thetry
block will be run and in the event of an exception/error, the code in thecatch
statement will run.
Inside the
catch
code block, logerror
to the console.
Since this exercise is an example, we’re using console.log()
to view the error. Generally, developers create a more sophisticated way of handling the error, like redirecting their users to another page, but logging is fine for us at the moment.
We’ll have to save the returned promise in a variable called
response
using theconst
keyword.response
will save the response of endpoint once that information has been sent back.Under
response
, create a conditional statement that checks if theok
property of theresponse
object evaluates to a truthy value.Inside the code block of the conditional statement,
await
the resolution of calling the.json()
method onresponse
.Save the returned object to a variable called
jsonResponse
using the keywordconst
.Since
.json()
is an asynchronous method we have toawait
until the promise status is resolved. Then we store the value to know what data the JSON holds.
Async POST Requests
Review :
GET and POST requests can be created a variety of ways.
Use AJAX to asynchronously request data from APIs.
fetch()
andasync
/await
are new functionalities developed in ES6 (promises) and ES8 respectively.Promises are a new type of JavaScript object that represent data that will eventually be returned from a request.
fetch()
is a web API that can be used to create requests.fetch()
will return promises.We can chain
.then()
methods to handle promises returned byfetch()
.The
.json()
method converts a returned promise to a JSON object.async
is a keyword that is used to create functions that will return promises.await
is a keyword that is used to tell a program to continue moving through the message queue while a promise resolves.await
can only be used within functions declared withasync
.
As with the other GET and POST requests that you’ve been making, an async
POST request requires more information. Take a look at the diagram.
We still have the same structure of using try
and catch
as before. But, in the fetch()
call, we now have to include an additional argument that contains more information like method
and body
.
Project using Foursquare & OpenWeather API
To be continued 1/12/2021
Last updated