USING THE WEB API SERVER FOR THE NEEDS OF ANOTHER WEB APPLICATION
using GET, POST, PUT, DELETE calls via JAVASCRIPT
In today's digital world, applications often need to communicate with other applications or services in order to function properly. For example, when we use mobile applications to search for products, book a hotel or check the weather forecast, these applications often connect to servers that provide the necessary information. This communication between client applications (such as mobile or web applications) and the server is done using a Web API (Application Programming Interface).
Web API is a set of rules and protocols that allow different software systems to communicate with each other over the Internet. Using standard protocols, such as HTTP (Hypertext Transfer Protocol), Web API allows applications to send and receive data from the server in a simple and organized way.
Web API is a set of rules and protocols that allow different software systems to communicate with each other over the Internet. Using standard protocols, such as HTTP (Hypertext Transfer Protocol), Web API allows applications to send and receive data from the server in a simple and organized way.
Introduction to Web API and REST architecture
The Web API enables the exchange of data between client applications and the server using the HTTP protocol. It is most often implemented using a REST (Representational State Transfer) architecture that uses standard HTTP methods for CRUD operations:
GET: Retrieves data from the server.
POST: Creates new resources.
PATH: Updates existing resources.
DELETE: Deletes resources.
REST APIs are simple, scalable, and enable communication between different applications on different platforms. Below we will explore how these methods are used in real-world examples.
The Web API enables the exchange of data between client applications and the server using the HTTP protocol. It is most often implemented using a REST (Representational State Transfer) architecture that uses standard HTTP methods for CRUD operations:
GET: Retrieves data from the server.
POST: Creates new resources.
PATH: Updates existing resources.
DELETE: Deletes resources.
REST APIs are simple, scalable, and enable communication between different applications on different platforms. Below we will explore how these methods are used in real-world examples.
In order to test the web API server, some of the existing web clients can be used: POSTMAN, OPEN API, etc., but this article will describe how to create a simple ASP.NET Core application that is created using only HTML, CSS and Javascript and which uses the web API application when it is necessary to place data in the database, edit or retrieve data from the database.
The application should display a list of some products, one or more, allow the creation of a new product, change the product data or delete it from the database.
In order to achieve this, the application, which we will call "WebAppProductsViewerForWebApi" in this text, needs to make GET, POST, PUT, PATCH, DELETE requests to the WEB API server. In doing so, both applications will be downloaded on the local computer, but will be on a different port.
The WEB API address will be: https://localhost:5001/, while the web application that communicates with it will be hosted at: https://localhost:5021/
The home page of this application can be seen in the following image:
The application should display a list of some products, one or more, allow the creation of a new product, change the product data or delete it from the database.
In order to achieve this, the application, which we will call "WebAppProductsViewerForWebApi" in this text, needs to make GET, POST, PUT, PATCH, DELETE requests to the WEB API server. In doing so, both applications will be downloaded on the local computer, but will be on a different port.
The WEB API address will be: https://localhost:5001/, while the web application that communicates with it will be hosted at: https://localhost:5021/
The home page of this application can be seen in the following image:
The picture shows a list of products whose data is in the SQL Server database, and with which the application communicates via the web API server. In order to display the mentioned list from javascript, an ajax GET request is sent, which returns data about all products. Above the list is "Highlighted product", that is, one product, the data of which will be obtained from the database also by means of a GET request, but in this case the one that returns data about one product for the sent product id.
You can also see the "New", "Edit" and "Delete" buttons, clicking on which opens new pages Create, html and Edit.html with input forms in the case of the first two, while for deletion (Delete eng.) it is called only method which is on the same page "Index.html". This allows making ajax calls to create a new one (POST), modify a specific one (PUT or PATCH), and delete a specific product. The complete creation of this application and analysis can be seen in the attached video material.
You can also see the "New", "Edit" and "Delete" buttons, clicking on which opens new pages Create, html and Edit.html with input forms in the case of the first two, while for deletion (Delete eng.) it is called only method which is on the same page "Index.html". This allows making ajax calls to create a new one (POST), modify a specific one (PUT or PATCH), and delete a specific product. The complete creation of this application and analysis can be seen in the attached video material.
Creation of WebAppProductsViewerForWebApi application - video material
video 1 |
video 2 |
video 3 |
video 4 |
A web application that displays a list of products is a simple application that uses HTML, CSS and javascript. It also uses the bootstrap framework for styling and adding functionality. Part of the initial index.html page is shown below, while the complete code can be seen at: github.com/slobodantrs/aspdotnet.git
Static files are located in the wwwroot folder, and how to set it up, see on the page: Servicing static web pages using a web server
The main functionality, i.e. calls to the web API application that communicates with the database takes place in the main.js file.
$(document).ready(function () {onStartLoad();}); let table; async function onStartLoad() {//call getData function getData().then((data) => { loadDataList(data); }) .catch((error) => { alert("Unable to get items." + error); });const idFeature=3; getFeatureData(idFeature).then((data) => { prikazFeatureData(data); }) .catch((error) => { alert("Unable to get items." + error); }); //log the data} async function getData() {//await the response of the fetch call /*GET method call in web API application*/ let response = await fetch("https://localhost:5001/products"); //proceed once the first promise is resolved. let data = await response.json(); //proceed only when the second promise is resolved return data;} async function loadDataList(data) {let product_list = document.querySelector("#productList"); table = document.createElement("table"); table.classList.add("productsTable"); product_list.appendChild(table); let i = 0; let row; for (key in data) {} async function getFeatureData(id) {var obj = data[key]; if (obj instanceof Object) {}if (i % 4 == 0) {}row = document.createElement("TR"); row.classList.add("d-flex"); row.classList.add("flex-row"); row.classList.add("justify-content-around"); //It has 4 div elements in a row table.appendChild(row); //Add row in the table} let h1Title = document.createElement("h2"); let priceParagraph = document.createElement("p"); let colorParagraph = document.createElement("p"); let sizeParagraph = document.createElement("p"); let quantityParagraph = document.createElement("p"); let btnDiv=document.createElement("div"); let aEdit=document.createElement("a"); let aDelete=document.createElement("a"); btnDiv.classList.add("d-flex"); aEdit.classList.add("btn"); aEdit.classList.add("btn-success"); aEdit.classList.add("text-white"); aEdit.setAttribute('href','edit.html?id='+obj.productId); aEdit.style.width = '100%'; aEdit.innerText = 'Edit'; aDelete.classList.add("btn"); aDelete.classList.add("btn-danger"); aDelete.classList.add("text-white"); aDelete.style.width = '100%'; aDelete.style.cursor = 'pointer'; aDelete.innerText = 'Delete'; const urlDel='https://localhost:5001/products/Delete/'+obj.productId; aDelete.onclick= function(){Delete(urlDel);}; h1Title.innerHTML = h1Title.innerHTML + obj.name; priceParagraph.innerHTML = priceParagraph.innerHTML + "Price: " + obj.price + " $"; colorParagraph.innerHTML = colorParagraph.innerHTML + "Color: " + obj.color; sizeParagraph.innerHTML = sizeParagraph.innerHTML + "Size: " + obj.size; quantityParagraph.innerHTML = quantityParagraph.innerHTML + "Quantity: " + obj.quantity; let column = document.createElement("TD"); column.appendChild(h1Title); column.appendChild(priceParagraph); column.appendChild(colorParagraph); column.appendChild(sizeParagraph); column.appendChild(quantityParagraph); column.appendChild(btnDiv);/*new*/ btnDiv.appendChild(aEdit);/*new*/ btnDiv.appendChild(aDelete);/*new*/ row.appendChild(column); i++;//await the response of the fetch call /*Poziv GET metode unutar web API aplikacije */ let response = await fetch("https://localhost:5001/products/"+id); //proceed once the first promise is resolved. let data = await response.json(); //proceed only when the second promise is resolved return data;} async function prikazFeatureData(data) {/*var dataArr = data["data"]; varijanta kad se spakuju podaci u JSON */ let nameOfArticleFeature = document.querySelector("#prod1"); let priceOfArticleFeature = document.querySelector("#prodPrice"); nameOfArticleFeature.innerHTML = data.name; priceOfArticleFeature.innerHTML = data.price + " $";} /*New*/ async function Delete(url) {await swal({}title: "Are you sure?", text: "You will not be able to recover this imaginary file!", icon: "warning", buttons: true, dangerMode: true,}).then((willDelete) => {if (willDelete) {});$.ajax({} else { }url: url, dataSrc: function (data) {});var json = JSON.parse(JSON.stringify(data)); return json;}, type: "DELETE", datatype: "json", success: function (data) {if (data.success) {},toastr.success(data.success); window.location.reload();} else {toastr.err(data.message);}
The javascript file shown above is a static file located in the js folder, which is like other static files inside the wwroot folder. This file is linked to the index.html page using the script tag:
<script type="text/javascript" src="js/main.js"></script>
First, the onStartLoad() function is executed, which then calls the getData() function. It is executed asynchronously and aims to collect product data, calling a web API application, which will read the data from the database and return a Promise object. Once all the data is collected using the json() function, it is converted to a JSON object, and then that object is returned from the getData() function as its return value.
If the response status is correct (200), then(data) is executed further and the data is passed to the loadDataList(data) function, otherwise, the catch(error) function will be executed to which the error message is passed. If the data is successfully returned from the web API application, it is further passed to the loadDataList(data) function, in the case of claiming the entire list of products, and in the case of claiming a single product, the getFeatureData(idFeature) method will be called. Both of these methods should place the data in the index.html page. The first creates a list of products, while the second displays the highlighted item whose id=3.
If the response status is correct (200), then(data) is executed further and the data is passed to the loadDataList(data) function, otherwise, the catch(error) function will be executed to which the error message is passed. If the data is successfully returned from the web API application, it is further passed to the loadDataList(data) function, in the case of claiming the entire list of products, and in the case of claiming a single product, the getFeatureData(idFeature) method will be called. Both of these methods should place the data in the index.html page. The first creates a list of products, while the second displays the highlighted item whose id=3.
This example shows how the web application, which in this case has the function of a client, sends requests to the web API service, requesting data from a database. In this case, it was shown how to make ajax GET requests via javascript.
The complete code is provided on GitHub, while the following table shows how to form other ajax calls to the web API service, which will produce POST, PUT and DELETE requests.
The complete code is provided on GitHub, while the following table shows how to form other ajax calls to the web API service, which will produce POST, PUT and DELETE requests.
WEB APLICATION | WEB API | ||
---|---|---|---|
description | ajax call | called method | returning value |
Product list request | //await the response of the fetch call |
GetAllProducts() |
Task < ActionResult < IEnumerable < Product > > > |
A product request with a specific ID | "
//await the response of the fetch call |
GetProduct(int id) |
Task < ActionResult < Product > >
|
Entering a new product into the database | var uriCreate = uri + "/Create"; |
Post(Product product) |
Task < ActionResult < int > > |
Updating a specific product | var uriUpdate = uri + "/Update"; |
PutAsync(int id,Product product)
|
Task < ActionResult < int > >
|
Deleting a specific product | const urlForDelete="..."; |
DeleteProduct(int id)
|
Task< ActionResult < int > >
|
Code examples:
Asynchronous communication with API
For asynchronous communication, you can use fetch or axios:
Fetch example:
For asynchronous communication, you can use fetch or axios:
Fetch example:
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
getData();
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
getData();
- Ovaj primer koristi fetch za slanje GET zahteva i asinkrono čeka odgovor koristeći async/await.
- Axios primer:
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
.then(response => console.log(response.data))
.catch(error => console.error(error));
- Axios pojednostavljuje rad sa API-jem i automatski parsira JSON odgovor.
Documentation and Resources
To continue learning and improving your skills with Web APIs and related technologies, here are some useful resources and documentation you can explore:
- ASP.NET Core Documentation
- Official documentation for ASP.NET Core. Here you can find everything you need to work with ASP.NET Core, including guides, references, and examples.
- Mozilla Developer Network (MDN) - JavaScript
- MDN offers a comprehensive guide to JavaScript, including basic concepts, functions, and examples.
- Postman Documentation
- Postman is a popular tool for testing Web APIs. Their documentation provides information on how to use Postman to send requests and test your API.
- OpenAPI Specification
- OpenAPI (formerly known as Swagger) is a standard for documenting REST APIs. Here you can learn how to use OpenAPI to create and document your APIs.
- JavaScript Tutorials on W3Schools
- W3Schools offers simple tutorials for JavaScript, including basic and advanced techniques.
- Axios Documentation
- Axios is a popular library for making HTTP requests in JavaScript. The documentation includes guides and examples for using Axios.
Summary and Final Notes
In summary, here are the key points covered:
- Importance of Web APIs
- Understanding how Web APIs enable communication between client applications and servers using the HTTP protocol.
- REST Architecture
- Familiarity with the basic methods of REST architecture (GET, POST, PUT, DELETE) and their application in real-world scenarios.
- Implementing Web APIs
- How to create a simple ASP.NET Core application that uses Web APIs and how to test Web APIs using tools like POSTMAN and OPEN API.
- Practical Example
- Demonstration of how a Web API can manage products in an application, including the use of GET, POST, PUT, PATCH, and DELETE requests.
- Security in Web APIs
- Basic information on authentication and authorization, as well as the importance of HTTPS for secure communication.