Let's get started!
REST API in JavaScript
We are going to discuss REST API in JavaScript using HTTP GET and POST request in extreme details. In this article, we are going to cover An HTTP Request Many Parts such as Methods(GET, POST, PUT, PATCH, DELETE), URL, Body, and Headers.
- The Basics of HTTP requests.
- An HTTP Request Parts.
- Example GET request.
- Example POST request.
- JavaScript Fetch Library.
- Making a GET Request in JavaScript.
- Making a POST Request in JavaScript.
- Adding Headers.
- Conclusion.
The Basics of HTTP Requests
To get a better understanding of what actually happens when we make a request to a REST API let’s go through the different parts of an HTTP request. This will make it easier to follow the coming parts of this REST API in the JavaScript tutorial.
HTTP, Hypertext Transfer Protocol, is the protocol that is used to send HTML pages just like the one that you are looking at right now over the internet. HTTP requests can also be made to fetch files such as images and videos, as well as data from a REST API.
HTTP, Hypertext Transfer Protocol, is the protocol that is used to send HTML pages just like the one that you are looking at right now over the internet. HTTP requests can also be made to fetch files such as images and videos, as well as data from a REST API.
An HTTP Request Consists of Many Parts
1. Method: Indicates what action you want to execute towards the server that you are making the request to. The valid methods are: An HTTP Request consists of five parts. REST API in JavaScript.
- GET for getting data from the server
- POST for creating data on the server
- PUT for updating data on the server
- PATCH for partially updating data on the server
- DELETE for deleting data on the server
2. URL: The URL that you want to access the server. In turn, the URL consists of the following parts: protocol, host and path. Let’s take a look at the URL http://example.com/about and split it into these parts. Web scraping API helps you to get an API without getting blocked. Below all three parts, we have to know.
- HTTP is the protocol used to access the server. REST APIs are served over HTTP or HTTPS.
- example.com is the host
- /about is the path
3. Body: The data that you want to send to the server. Usually consists of a JSON formatted string.
4. Headers: Extra data for the request such as access tokens and information about your browser.
Let’s take a look at a couple of example requests and go through the parts of each one.
Example GET Request
Method | URL | Body | Headers |
GET | http://example.com?page=1&tab=2 |
GET is the method used to make the request. GET is usually used for fetching data from a server. When you visited this page and any other page through your browser a GET request is made to the address that you type into the address bar. GET requests can’t have a body so that is empty.
HTTP:// is the protocol that the request is made with.
example.com is the hostname and points to a server somewhere connected to the internet. I hope you are enjoying using the REST API in JavaScript Solution.
The URL also contains the string ?page=1&tab=2 at the end. This string is called query parameters and can be used to send additional information to the server. The server can then respond according to the information provided. In this case, there are two query parameters:
the page which is equal to 1, this could be used by the server to display the correct page on example.com. the tab which is equal to 2, this could be used by the server to display text inside a specific tab on the page.
The body is empty for GET requests since they don’t contain any JSON data that we want to send to the server.
HTTP:// is the protocol that the request is made with.
example.com is the hostname and points to a server somewhere connected to the internet. I hope you are enjoying using the REST API in JavaScript Solution.
The URL also contains the string ?page=1&tab=2 at the end. This string is called query parameters and can be used to send additional information to the server. The server can then respond according to the information provided. In this case, there are two query parameters:
the page which is equal to 1, this could be used by the server to display the correct page on example.com. the tab which is equal to 2, this could be used by the server to display text inside a specific tab on the page.
The body is empty for GET requests since they don’t contain any JSON data that we want to send to the server.
Example POST Request
Method | URL | Body | Headers |
POST | http://example.com/ posts | { “message”: “Hello World!” } | User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0 |
This has the POST method which is usually used to create things through a REST API. POST, PUT, PATCH and DELETE requests can have a body. In this case, the body is:
{
"message": "Hello World!"
}
Okay, now we'll dive into the code!
Introducing the JavaScript Fetch Library
The easiest way to call a REST API in JavaScript is to use the fetch library. It is built into the standard JavaScript library and can be used to make all sorts of HTTP calls. Documentation for the fetch library can be found at Moz but we will cover everything you need to interact with a REST API in this tutorial.
When running JavaScript in the browser there is no need to import anything. Simply use fetch like this
fetch('http://example.com');
This will make an HTTP call to http://example.com. In the next chapters, we will learn how to display the data and how to make different types of requests.
Making a GET Request in JavaScript
Now that we know the basics about GET requests and the fetch API, let's make a GET request in JavaScript!
For this tutorial, I have created a mock API using a tool called Mocki. You can use the API URL that I use in the examples, create your own mock or use a real API of your choosing.
Since the default method in fetch is GET we don't need to specify it in the function call. We simply need to do the following: Below is the example of REST API in JavaScript by Mock API.
fetch('https://api.mocki.io/v1/b13e0144')
.then(response => response.json())
.then(data => console.log(data);
This should log the following to the console:
{
"berries": ["strawberry", "blueberry", "raspberry"]
}
Now we can fetch data from the server.
Making a POST Request in JavaScript
This is an important part of REST API in JavaScript, Now learn to make a POST request in Javascript. Time to try our hands-on making a POST request. Since this is not the default method in the fetch API we need to add it in the fetch() call. We also need to add some data to our request, in this case, we will pass an empty object ({}) as the body.
fetch('https://api.mocki.io/v1/ddb6d39b', { method: 'POST', body: {} })
.then(response => response.json())
.then(data => console.log(data);
This time the following should be logged to the console:
{
"status": "OK"
}
The same structure can be used for PUT, DELETE and PATCH requests. Just use the correct method in the call to fetch().
Adding Headers
In many cases, we need to add headers to interact with a REST API. Typically you need an API key that is usually passed as a header to the API. In this example, we add an API key as a header when making a GET request. In adding the header please keep in mind the method and response to using REST API in JavaScript.
fetch('https://api.mocki.io/v1/b13e0144', { method: 'POST', headers: {
'x-api-key': '9ff709f9-a598-4934-9f9b-cbb889ecbc03' } })
.then(response => response.json())
.then(data => console.log(data);
Using the fetch library is a quick and easy way to interact with REST APIs in JavaScript. While there are more advanced libraries out there fetch supports all types of HTTP requests and should cover everything you need to use a REST API as a beginner.
- What parts an HTTP request consists of
- How a couple of common requests can be structured.
- How to make API requests in JavaScript including data in the body as well as headers.
Thanks for reading and good luck integrating towards your next REST API.
0 Comments: