
JavaScript is a powerful programming language that can be used to Call Web API directly from the browser. In this tutorial, I will show you how to call a Web API using JavaScript, specifically with the XMLHttpRequest (XHR) object. I have already created a Web API built with ASP.NET Core that follows the RESTful pattern and supports all the essential CRUD operations. The API provides flight reservation data to clients in JSON format and allows clients to search reservations by ID, update existing reservations, delete reservations, and perform other related operations. I will use JavaScript and the XHR object to communicate with this API.
This tutorial is a part of the ASP.NET Core API series which contains 5 tutorials to master this area:
So let us Call the different method of the Web API from JavaScript and perform all the essential CRUD operations — Creating, Reading, Updating, and Deleting flight reservations. Stay tuned till the end as I will also show you how to upload Image file with API using JavaScript. Make sure to follow the tutorial through to the end, as you will find complete working examples for each operation. The source code for the entire tutorial is also available for download from the link provided at the end of the article.
Page Contents
The XMLHttpRequest (XHR) object is one of the traditional and widely used ways to call a REST API from JavaScript. It allows JavaScript to send HTTP requests to a Web API and receive data from a URL without requiring a full page refresh. This makes it possible to build more responsive and interactive web applications. Modern JavaScript also provides other approaches for communicating with APIs, including the Fetch API and Promises, which offer cleaner and more flexible ways to handle asynchronous API requests.
The ASP.NET Core Web API includes an endpoint that retrieves and returns all flight reservations in JSON format. The method signature for this API endpoint is shown below:
[HttpGet]
public IEnumerable<Reservation> Get()
{
//… return all the reservations
}Next, I will Call this Web API GET method from JavaScript to retrieve all flight reservations. Create a new HTML page named AllReservation.html (or use any name you prefer). On this page, JavaScript will send a GET request to the Web API, receive the reservation data in JSON format, and display the results in an HTML table. The table markup is shown below.
<table id="apiTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Start Location</th>
<th>End Location</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Initially, the <tbody> element is left empty because the reservation records will be dynamically added to the table after they are retrieved from the Web API.
Next, add the following JavaScript code inside the <script> tag on the page:
<script type="text/javascript">
ShowAllReservation();
function ShowAllReservation() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://localhost:44324/api/Reservation", true);
xhttp.send();
xhttp.onreadystatechange = function () {
var tbody = document.getElementById("apiTable").querySelector("tbody");
tbody.innerHTML = "";
if (this.readyState == 4 && this.status == 200) {
JSON.parse(this.responseText).forEach(function (data, index) {
tbody.innerHTML += "<tr><td>" + data.id + "</td>" + "<td>" + data.name + "</td>" + "<td>" + data.startLocation + "</td>" + "<td>" + data.endLocation + "</td></tr>";
});
}
};
}
</script> When the page loads, the JavaScript function named ShowAllReservation() is executed. This function uses the XMLHttpRequest (XHR) object to send a request to the Web API and retrieve the reservation data. The code for making the API call is shown below:
var xhttp = new XMLHttpRequest();I am making an HTTP GET type request to the URL of my API’s method which will return all these reservations. This URL is:
https://localhost:44324/api/ReservationThe API returns the reservations in JSON as shown below:
[
{
"id": 1,
"name": "Ankit",
"startLocation": "New York",
"endLocation": "Beijing"
},
{
"id": 2,
"name": "Bobby",
"startLocation": "New Jersey",
"endLocation": "Boston"
},
{
"id": 3,
"name": "Jacky",
"startLocation": "London",
"endLocation": "Paris"
}
]
The onreadystatechange event handler is triggered when the XHR request state changes and, once the API response has been successfully received, the returned JSON data can be processed. In this handler, we can read the reservation data and dynamically add each reservation to the HTML table.
The following image shows the flight reservations returned by the Web API and displayed in the HTML table:

The the working image for the whole process:
My ASP.NET Core API also provides a GET Endpoint for retrieving a specific flight reservation by its ID. The method accepts the reservation ID and returns the corresponding reservation. Its definition is shown below:
[HttpGet("{id}")]
public ActionResult<Reservation> Get(int id)
{
if (id == 0)
return BadRequest("Value must be passed in the request body.");
return Ok(repository[id]);
}To Call this Web API GET method from JavaScript, I need to include the reservation ID in the API request URL. Start by creating a new HTML page named GetReservation.html. This page contains three main elements:
The code for this page is shown below. I will start with the HTML markup, which contains the input field for entering the reservation ID, a button to initiate the API request, and an HTML table for displaying the returned reservation details.
<input type="text" class="form-control" id="Id" />
<button id="GetButton" onclick="GetReservation()">Get Reservation</button>
<table id="apiTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Start Location</th>
<th>End Location</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Next, add the following JavaScript code, which handles the API call and retrieves the reservation details from the Web API.
<script type="text/javascript">
function GetReservation() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://localhost:44324/api/Reservation/" + document.getElementById("Id").value, true);
xhttp.send();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var tbody = document.getElementById("apiTable").querySelector("tbody");
tbody.innerHTML = "<tr><td>" + response.id + "</td><td>" + response.name + "</td><td>" + response.startLocation + "</td><td>" + response.endLocation + "</td></tr>";
}
};
}
</script>The JavaScript code is similar to the code used in the previous example. The main difference is that the reservation ID is appended to the Web API URL. This allows the API to identify and return the specific reservation requested by the user. The relevant code is shown below:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://localhost:44324/api/Reservation/" + document.getElementById("Id").value, true);The API response, which contains the reservation details in JSON format, is processed by JavaScript and displayed in the HTML table. The reservation data is dynamically appended to the table’s <tbody> element, as shown below:
tbody.innerHTML = "<tr><td>" + response.id + "</td><td>" + response.name + "</td><td>" + response.startLocation + "</td><td>" + response.endLocation + "</td></tr>";I have created a small video which shows the working of this search feature:

Did you know that you can also upload files to a remote server using a Web API? In this section, I will show you how to implement file uploads with JavaScript using just a few lines of code.
The Web API includes an endpoint that accepts files uploaded by clients. The files are sent as part of a multipart form request. The following code shows the Web API method responsible for receiving and processing the uploaded files:
[HttpPost("UploadFile")]
public async Task<string> UploadFile([FromForm] IFormFile file)
{
string path = Path.Combine(hostingEnvironment.WebRootPath, "Images/" + file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return "https://localhost:44324/Images/" + file.FileName;
}
Next, we will call this Web API method from JavaScript to upload the file to the server. The selected file will be added to a FormData object, which is then sent to the Web API as part of the HTTP request. This approach allows JavaScript to upload files without requiring a full page refresh.
So, create a new page and call it AddFile.html. To it add 2 html tags:
<input type="file" id="File" />
<button id="AddButton" onclick="UploadFile()" type="submit">Add</button>Next, add the following JavaScript code to make the API request using the XMLHttpRequest (XHR) object:
<script type="text/javascript">
function UploadFile() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://localhost:44324/api/Reservation/UploadFile", true);
data = new FormData();
data.append("file", document.getElementById("File").files[0]);
xhttp.send(data);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert(this.response);
}
};
}
</script>
I am making an HTTP POST request to the Web API using the XMLHttpRequest (XHR) object. The request is sent to the following API URL:
https://localhost:44324/api/Reservation/UploadFileNext, I add the selected file to the FormData object:
data = new FormData();
data.append("file", document.getElementById("File").files[0]);Finally, I send the request to the Web API by calling the XHR send() method and passing the FormData object as the request body:
xhttp.send(data);Check this video for understanding the working of this feature:

Note: In this video, I am uploading an image file and displaying the uploaded image in an <img> element after the upload is completed. However, the same approach can be used to upload other types of files, such as PDFs, documents, spreadsheets, and more, depending on what the Web API is configured to accept.
The ASP.NET Core Web API provides a POST endpoint for creating a new flight reservation. It accepts the reservation details from the body of the HTTP request and uses this data to add a new reservation
The code of this method is given below:
[HttpPost]
public IActionResult Post([FromBody] Reservation res)
{
//… add reservation to the database
}Now let us Call the POST Method of Web API from JavaScript. So, create a new html page called AddReservation.html and add the following code to it:
<input type="text" id="Name" />
<input type="text" id="StartLocation" />
<input type="text" id="EndLocation" />
<button type="submit" onclick="AddReservation()">Add</button>
<table id="apiTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Start Location</th>
<th>End Location</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
The page contains three text boxes for entering the Name, Start Location, and End Location of the new reservation. When the user clicks the button, JavaScript calls the Web API and sends the entered reservation details to the server.
The HTML table is then updated to display the newly added reservation.
Next, add the following JavaScript code to the page to make the request to the Web API:
<script type="text/javascript">
function AddReservation() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://localhost:44324/api/Reservation", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Key", "Secret@123");
var obj = { Id: 0, Name: document.getElementById("Name").value, StartLocation: document.getElementById("StartLocation").value, EndLocation: document.getElementById("EndLocation").value };
xhttp.send(JSON.stringify(obj));
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var tbody = document.getElementById("apiTable").querySelector("tbody");
tbody.innerHTML = "<tr><td>" + response.id + "</td><td>" + response.name + "</td><td>" + response.startLocation + "</td><td>" + response.endLocation + "</td></tr>";
}
};
}
</script>The Web API call is made with JavaScript to this URL https://localhost:44324/api/Reservation.
It is important to note that the ASP.NET Core Web API endpoint used to create a new reservation is protected and requires valid credentials. Therefore, when calling the API from JavaScript, we need to include the required authentication credentials in the request. These credentials are added to the headers of the XMLHttpRequest object before the request is sent, as shown below:
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Key", "Secret@123");Next, the new reservation details are retrieved from the text boxes and prepared for submission through the XMLHttpRequest object. The following code shows how the entered data is added to the request:
var obj = { Id: 0, Name: document.getElementById("Name").value, StartLocation: document.getElementById("StartLocation").value, EndLocation: document.getElementById("EndLocation").value };
xhttp.send(JSON.stringify(obj));After the reservation is successfully added, the Web API returns the newly created reservation in its response. JavaScript then processes this response and displays the newly added reservation in the HTML table on the page.
I have also created a short video demonstrating how this feature works. You can watch it below:

Did you know that jQuery can also make Web API calls and handle complete CRUD operations with just a few lines of code? If you prefer jQuery over the native XMLHttpRequest approach, I have created a complete tutorial that walks you through Creating, Reading, Updating, and Deleting data using a Web API with jQuery.
👉 Check out How to Call Web API from jQuery and learn how to build the entire feature from scratch.
The HTTP PUT method in the Web API is responsible for updating an existing flight reservation. It receives the updated reservation details and applies the changes to the corresponding record. The method definition is shown below:
[HttpPut]
public Reservation Put([FromForm] Reservation res)
{
//…
}So, we can Call this Web API PUT method from JavaScript and update any reservation. Start by creating a new HTML page called UpdateReservation.html. Then add the following HTML to this page:
<input type="text" id="Id" readonly />
<input type="text" id="Name" />
<input type="text" id="StartLocation" />
<input type="text" id="EndLocation" />
<button type="submit" onclick="UpdateReservation()">Update</button>
<table id="apiTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Start Location</th>
<th>End Location</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
The page contains several input text boxes where users can enter the updated values for an existing reservation. After providing the new details, the user clicks the Update button to send the changes to the Web API. Once the update is successful, the updated reservation is displayed in the HTML table, allowing the user to immediately see the changes.
Now add the following JavaScript code to your page. As usual I am making use of XMLHttpRequest for calling the API, also I have specified the PUT type of request on the open method of XHR.
<script type="text/javascript">
GetReservation();
function UpdateReservation() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var tbody = document.getElementById("apiTable").querySelector("tbody");
tbody.innerHTML = "<tr><td>" + response.id + "</td><td>" + response.name + "</td><td>" + response.startLocation + "</td><td>" + response.endLocation + "</td></tr>";
}
};
xhttp.open("PUT", "https://localhost:44324/api/Reservation", true);
data = new FormData();
data.append("Id", document.getElementById("Id").value);
data.append("Name", document.getElementById("Name").value);
data.append("StartLocation", document.getElementById("StartLocation").value);
data.append("EndLocation", document.getElementById("EndLocation").value);
xhttp.send(data);
}
function GetReservation() {
let params = (new URL(document.location)).searchParams;
let id = params.get("id");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
document.getElementById("Id").value = response.id;
document.getElementById("Name").value = response.name;
document.getElementById("StartLocation").value = response.startLocation;
document.getElementById("EndLocation").value = response.endLocation;
}
};
xhttp.open("GET", "https://localhost:44324/api/Reservation/" + id, true);
xhttp.send();
}
</script>
When the page loads, the GetReservation() function is executed to retrieve the reservation details from the Web API. It sends the reservation ID to the API and fetches the corresponding reservation data. This is similar to the approach we used earlier when calling the Web API GET method to retrieve a specific reservation.
In this example, the reservation ID is passed to the page through the URL query string. JavaScript reads this ID from the URL using the following two lines of code:
let params = (new URL(document.location)).searchParams;
let id = params.get("id");When the API response is received, JavaScript processes the returned reservation data and displays it in the HTML table on the page.
The UpdateReservation() function is executed when the user clicks the Update button. Inside this function, JavaScript sends a request to the Web API to update the selected reservation.
Before making the API call, the updated reservation values are collected from the input fields and added to a FormData object, as shown below:
data = new FormData();
data.append("Id", document.getElementById("Id").value);
data.append("Name", document.getElementById("Name").value);
data.append("StartLocation", document.getElementById("StartLocation").value);
data.append("EndLocation", document.getElementById("EndLocation").value);And then I add the ‘FormData’ object to the XMLHttpRequest as a parameter.
xhttp.send(data);I have created a small video that shows it’s working:

Note: You can easily link the UpdateReservation.html page from AllReservation.html by adding a new <td> element to the reservation table and placing an anchor inside it. The anchor can pass the reservation ID in the URL and open the corresponding reservation on the update page.
The required changes are shown below:
1. Add update ‘th’ on the ‘thead’ area:
<table id="apiTable">
<thead>
<tr>
//…
<th>Update</th>
</tr>
</thead>
<tbody></tbody>
</table>2. Add a new ‘td’ element to the ‘tbody’ element and create a link that contains the ‘id’ of the reservation in query string.
tbody.innerHTML += "<tr><td>" + data.id + "</td>" + "<td>" + data.name + "</td>" + "<td>" + data.startLocation + "</td>" + "<td>" + data.endLocation + "</td>" + "<td><a href=\"UpdateReservation.html?id=" + data.id + "\">Update</a></td></tr>"; Now, let’s take a look at another way to update reservations by calling the HTTP PATCH based API method. Unlike PUT, PATCH is typically used when you want to update only specific properties of an existing reservation rather than replacing the entire resource.
The below image explains the whole flow:
The API method is defined as follows:
[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
//…
}It has 2 parameters – ‘id’ of the reservation that needs to be updated and JsonPatchDocument object that will contain the new reservation values.
So, create a new html page called UpdateReservationPatch.html and add 3 text boxes for taking new values for the reservation, and a button.
<input type="text" id="Id" readonly />
<input type="text" id="Name" />
<input type="text" id="StartLocation" />
<input type="text" id="EndLocation" />
<button type="submit" onclick="UpdateReservation()">Update</button>
Next, add the following JavaScript code which will Call Web API PATCH method from JavaScript and update the reservation.
<script type="text/javascript">
GetReservation();
function GetReservation() {
let params = (new URL(document.location)).searchParams;
let id = params.get("id");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
document.getElementById("Id").value = response.id;
document.getElementById("Name").value = response.name;
document.getElementById("StartLocation").value = response.startLocation;
document.getElementById("EndLocation").value = response.endLocation;
}
};
xhttp.open("GET", "https://localhost:44324/api/Reservation/" + id, true);
xhttp.send();
}
function UpdateReservation() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
window.location.href = "AllReservation.html";
}
};
let params = (new URL(document.location)).searchParams;
let id = params.get("id");
var data = JSON.stringify([
{
op: "replace",
path: "Name",
value: document.getElementById("Name").value
},
{
op: "replace",
path: "StartLocation",
value: document.getElementById("StartLocation").value
},
{
op: "replace",
path: "EndLocation",
value: document.getElementById("EndLocation").value
}
]);
xhttp.open("PATCH", "https://localhost:44324/api/Reservation/" + id, true);
xhttp.setRequestHeader("Content-type", "application/json-patch+json");
xhttp.send(data);
}
</script>
When the user clicks the Update button, the UpdateReservation() JavaScript function is executed. Inside this function, I retrieve the reservation ID from the URL query string using the following code:
let params = (new URL(document.location)).searchParams;
let id = params.get("id");Next, I convert the updated reservation values entered in the three text boxes into a JSON string using JavaScript’s JSON.stringify() method. This JSON data can then be sent to the Web API as part of the PATCH request, as shown below:
var data = JSON.stringify([
{
op: "replace",
path: "Name",
value: document.getElementById("Name").value
},
{
op: "replace",
path: "StartLocation",
value: document.getElementById("StartLocation").value
},
{
op: "replace",
path: "EndLocation",
value: document.getElementById("EndLocation").value
}
]);And then finally making the Call to the Web API with XHR object as given below:
xhttp.open("PATCH", "https://localhost:44324/api/Reservation/" + id, true);
xhttp.setRequestHeader("Content-type", "application/json-patch+json");
xhttp.send(data);Check the functionality which is shown by the below video:

The Web API also provides a method for deleting a reservation. This method accepts the reservation ID as a parameter and uses it to identify the reservation that should be removed. Its definition is shown below:
[HttpDelete("{id}")]
public void Delete(int id){
//… delete the reservation
}The delete reservation feature will be added to the existing AllReservation.html page that we created earlier. To add this functionality, we need to make a few changes to the HTML table that displays the reservation records.
Perform the following changes to the table on the AllReservation.html page:
1. Add delete ‘th’ on the ‘thead’ area:
<table id="apiTable">
<thead>
<tr>
//…
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
2. Add a new ‘td’ element to the ‘tbody’ element that contains a ‘cross’ image. When this image is clicked the delete operation is preformed.
tbody.innerHTML += "<tr><td>" + data.id + "</td>" + "<td>" + data.name + "</td>" + "<td>" + data.startLocation + "</td>" + "<td>" + data.endLocation + "</td>" + "<td><a href=\"UpdateReservation.html?id=" + data.id + "\"><img src=\"icon/edit.png\" /></a></td>" + "<td><img class=\"delete\" src=\"icon/close.png\" /></td></tr>"; Next, add the following JS function called ‘CreateClickEvent()’ in your page:
function CreateClickEvent() {
var dimg = document.getElementsByClassName("delete");
for (let i = 0; i < dimg.length; i++) {
dimg[i].addEventListener("click", function (e) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
ShowAllReservation();
};
var resId = e.target.closest("tr").childNodes[0].innerHTML;
xhttp.open("DELETE", "https://localhost:44324/api/Reservation/" + resId, true);
xhttp.send();
})
}
}Also make sure you update the ShowAllReservation() function so that you call the CreateClickEvent() function from inside the xhttp.onreadystatechange handler. I have shown this below:
function ShowAllReservation() {
//…
xhttp.onreadystatechange = function () {
//…
if (this.readyState == 4 && this.status == 200) {
//…
CreateClickEvent();
}
};
}
Once the reservations are fetched from the API, I am creating click event on all the delete images i.e. the cross image. So I am calling the CreateClickEvent() function from inside the http.onreadystatechange handler.
I am grabbing all the click images by their CSS class as:
var dimg = document.getElementsByClassName("delete");I am then looping through each of them and adding a click event to them by using the addEventListener function of JS:
for (let i = 0; i < dimg.length; i++) {
dimg[i].addEventListener("click", function (e) {
//…
})
}Before making the API call to delete a reservation I should get it’s id from the first td of the row which is done by using the below code:
var resId = e.target.closest("tr").childNodes[0].innerHTML;And finally making the Call to the Web API DELETE method from JavaScript. Note that I am passing the reservation id to the URL also.
xhttp.open("DELETE", "https://localhost:44324/api/Reservation/" + resId, true);Test this feature by clicking the cross icon against any reservation object and the API will delete it. Check the below video which shows the delete process:

The link to download the full source code of this tutorial is given below:
In this tutorial, we explored how to call a Web API from JavaScript using the XMLHttpRequest (XHR) object. We covered the complete CRUD workflow, including retrieving, creating, updating, and deleting reservations, as well as uploading files to an ASP.NET Core Web API. The examples provide a practical foundation for integrating JavaScript applications with RESTful APIs. You can download the complete source code and use it freely in your own projects and websites.