5/13/2020

REST API in JavaScript- GET & POST Request | 2 Speedy Ex.

In this tutorial, we are going through GET and POST REST API in JavaScript, and we will walk you through how to interact with REST APIs in JavaScript. This is a key skill that you need when working with frontend development or web development in general. REST APIs are interfaces that you call through HTTP just like when you visit this website. The difference is that you usually make these calls to get and store data in a structured format such a JSON. The data can then be displayed on a website or app.

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.

  1. The Basics of HTTP requests.
  2. An HTTP Request Parts.
  3. Example GET request.
  4. Example POST request.
  5. JavaScript Fetch Library.
  6. Making a GET Request in JavaScript.
  7. Making a POST Request in JavaScript.
  8. Adding Headers.
  9. Conclusion.

REST API in JavaScript

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 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.

An HTTP Request Consists of Many Parts


1. Method: Indicates what you 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.

  1. GET for getting data from the server
  2. POST for creating data on the server
  3. PUT for updating data on the server
  4. PATCH for partially updating data on the server
  5. 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.

  1. HTTP is the protocol used to access the server. REST APIs are served over Http or https.
  2. example.com is the host
  3. /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


MethodURLBodyHeaders
GEThttp://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.

Example POST Request


MethodURLBodyHeaders
POSThttp://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 are able to 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 header please keep in mind about 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.

Conclusion


In this using REST API in JavaScript, tutorial we have learned:

  1. What parts an HTTP request consists of
  2. How a couple of common requests can be structured.
  3. 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.
Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: