How to Make An Authorize API Call With Fetch API

Introduction

In this article, I will explain the Fetch API and how we can make an authorized Post request to an API with Fetch(). So before we go deep down into making an authorized Fetch call, I want to explain what Fetch API is.

How to Make An Authorize API Call With Fetch API

What is Fetch API, and how does it work?

In simple words, we can say that JavaScript Provides the Fetch API whenever we need to get or post some data from the API. We can simply get data by making a get request, and also we can post data by a Post request. Fetch API is beneficial and convenient. It has an easy syntax.

Syntax 

fetch(url)
.then(response => {
// return or check the response here 
});

In this syntax, we can see that first, we used the fetch method, and here we need to pass the URL of the API; we can also pass the headers by putting the coma(,)after the URL. We can also pass Content-Type with the header. In the case of an Authorize Api call, we can pass our token also here. Next, we used the then statement with the response. Here can check our response. And next, we can return the response to the next layer. The fetch API works with the promises; if you are not familiar with the promises, don't worry; I will explain here.

Why do we use Promises in JavaScript?

How to Make An Authorize API Call With Fetch API

In Javascript, we use promises as an asynchronous call to get OR post data. In JavaScript, Promises can contain one of these states.

  • pending- This one is an initial state; in this state, the promise is not completed or not rejected.
  • fulfilled- In this state, our Task is completed successfully.
  • rejected-  If you get the rejected state, the task is failed.

Now let's make n call; I have an authenticated API with the Bearer token. I will make an authorized post call to save some data into the server using JS fetch() API. To make this call, we need a few things.

  • API URL or Endpoint.-// https://localhost:7068/api/comment/CommentPost
  • Bearer token            -//eyJhbGciOiJIUzI1NiIs**************************************************ydmljZUFjY2Vzc1
  • Well-formed data that is valid for that Endpoint.

Test-Data

var comment = {
    contentId: "61",
    fromUserId: "gt656",
    comment: "Great idea",
};

Note. If you haven't allowed CORS (Cross-Origin Resource Sharing) in your API, you first need to allow CORS in your API. If you have no idea about CORS, don't worry. I'm going to explain about CORSE.

CORS

How to Make An Authorize API Call With Fetch API

Whenever we make an API or server and want to use it from different origins, we need to allow Cross Origine Resource Sharing. If we don't turn it on, we'll not be able to access that endpoint from different origins because, due to security reasons, by default is turned off.

I'm using a .NETCore API, so I have added this code to my program.cs to allow CORS.

builder.Services.AddCors(policyBuilder =>
            policyBuilder.AddDefaultPolicy(policy =>
            policy.WithOrigins("*").AllowAnyHeader().AllowAnyHeader())
) ;
// use this line after --> var app = builder.Build();
app.UseCors();

In this Code, I added the policy related to CORS and middleware to use CORS. If you don't allow CORS in your API, you must face errors in your API call. So please ensure that CORS is allowed if your server and clients are not from the same origin.

Now let's make a call to the API,

async function postComment() {
    try {
        var comment = {
            contentId: "61",
            fromUserId: "gt656",
            comment: "Great idea",
        };
        const url = 'https://localhost:7068/api/comment/CommentPost';
        const data = comment;
        const headers = new Headers({
            'Authorization': 'Bearer eyJhbG*************************************************************************************************************EizVFR9UAgPAQ6OOQZJI83q9QDkvigfWpM',
            'Content-Type': 'application/json'
        });
        await fetch(url, {
            headers: headers,
            method: 'POST',
            mode: 'cors',
            body: JSON.stringify(data)
        }).then(resp => resp.json()).then(json => {
            response = json
            console.log(response)
        }).catch(error => console.log(error))
        return response;
    } catch (error) {
        console.error(error);
        return false;
    }
}

Here in this code, I have a function posting data to the given Endpoint. I have initiated the header with the valid value. In case of an authorized call, pass the headers just after the URL. The fetch() API uses two .then statements in the first .then statement; we can check whether the response is fulfilled, rejected, or pending. In the second .then statement, we can print or return the response. For testing, I'm printing the response with the console.log() method, and here is the output.

How to Make An Authorize API Call With Fetch API

In my case, I'm getting my desired response. You'll get the response that is built by your API.

Conclusion

In this article, we have discussed the JavaScript fetch() API and also about making an authorized call to a  secure endpoint. We have also learned about CORS and how to enable CORS on your server. We used the Bearer token to secure our server and passed that token to the headers. 


Similar Articles