In the world of web development, knowing how to communicate with HttpClient is crucial for creating dynamic and interactive web applications. HTTP (Hypertext Transfer Protocol) is the foundation of data exchange on the internet, enabling communication between frontend applications and backend services. This blog will delve into the details of how to communicate with HttpClient , covering various HTTP methods and providing a comprehensive example to illustrate these concepts in action.
What is HTTP?
Hypertext requests and data are sent across the internet using the HTTP protocol. It is the backbone of data transmission for the World Wide Web, facilitating the flow of website data between web clients and servers via HTTP.
Key Components of HTTP
- Requests: Communications sent to the server by the client to start a process.
- Reactions: The server’s messages in response to the client’s inquiry.
- Techniques: Specify the kind of operation (GET, POST, PUT, DELETE, etc.) that the client wishes to carry out.
- Status codes (200 OK, 404 Not Found, 500 Internal Server Error, etc.): These codes indicate the outcome of the request.
HTTP Methods
GET
The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and have no other effect. GET requests can be cached and remain in the browser history.
Example:
GET /books HTTP/1.1
Host: example.com
POST
The POST method submits data to be processed to a specified resource. It is often used when submitting form data or uploading a file. Unlike GET requests, POST requests do not get cached and do not remain in the browser history.
Example:
POST /books HTTP/1.1
Host: example.com
Content-Type: application/json
{
"title": "New Book",
"author": "Author Name"
}
PUT
The PUT method replaces all current representations of the target resource with the request payload. It is used to update an existing resource or create a new one if it does not exist.
Example:
PUT /books/1 HTTP/1.1
Host: example.com
Content-Type: application/json
{
"title": "Updated Book",
"author": "Updated Author"
}
DELETE
The DELETE method deletes the specified resource. It is used to remove a resource from the server.
Example:
DELETE /books/1 HTTP/1.1
Host: example.com
PATCH
The PATCH method applies partial modifications to a resource. It is used when you need to update a part of the resource rather than the whole resource.
Example:
PATCH /books/1 HTTP/1.1
Host: example.com
Content-Type: application/json
{
"title": "Partially Updated Book"
}
HTTP Status Codes
A server responds to a request from a client by returning an HTTP status code. They fall into five different categories:
1xx: Informational
- 100 Continue: The server has received the request headers, and the client should proceed to send the request body.
2xx: Success
- 200 OK: The request has succeeded.
- 201 Created: The request has been fulfilled, resulting in the creation of a new resource.
3xx: Redirection
- 301 Moved Permanently: The requested resource has been assigned a new permanent URI.
4xx: Client Error
- 400 Bad Request: The server could not understand the request due to invalid syntax.
- 401 Unauthorized: The client must authenticate itself to get the requested response.
- 404 Not Found: The server cannot find the requested resource.
5xx: Server Error
- 500 Internal Server Error: The server has encountered a situation it doesn’t know how to handle.
- 503 Service Unavailable: The server is not ready to handle the request.
Communicate with HttpClient : An Example
Let’s go over an in-depth example of utilizing HTTP to communicate with a backend service. To maintain a list of books, we’ll build a basic web application that communicates with a backend server.
Reverse Engineering
We will make use of BookAPI, a fictitious backend service. This service offers APIs for managing a list of books using the CRUD (Create, Read, Update, Delete) process.
Front-end Program
In order to communicate with the BookAPI service, our front-end application will be a straightforward HTML page with JavaScript.
Step 1: Setting Up the Backend Service
For the sake of this example, we’ll use a mock service. Below are the endpoints provided by BookAPI
:
- GET /books: Retrieve a list of books.
- POST /books: Add a new book.
- PUT /books/: Update an existing book.
- DELETE /books/: Delete a book.
Step 2: Creating the Frontend Application
Create an index.html
file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Manager</title>
<style>
body {
font-family: Arial, sans-serif;
}
.book-list {
margin: 20px 0;
}
.book-item {
padding: 10px;
border-bottom: 1px solid #ccc;
}
.book-item:last-child {
border-bottom: none;
}
.book-form {
margin: 20px 0;
}
.book-form input,
.book-form button {
padding: 10px;
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Book Manager</h1>
<div class="book-form">
<input type="text" id="book-title" placeholder="Book Title">
<button onclick="addBook()">Add Book</button>
</div>
<div class="book-list" id="book-list">
<!-- Book items will be displayed here -->
</div>
<script src="app.js"></script>
</body>
</html>
Step 3: Writing the JavaScript Code
Create an app.js
file with the following content:
document.addEventListener('DOMContentLoaded', fetchBooks);
const API_URL = 'https://mockapi.io/api/v1/books';
async function fetchBooks() {
try {
const response = await fetch(API_URL);
const books = await response.json();
displayBooks(books);
} catch (error) {
console.error('Error fetching books:', error);
}
}
function displayBooks(books) {
const bookList = document.getElementById('book-list');
bookList.innerHTML = '';
books.forEach(book => {
const bookItem = document.createElement('div');
bookItem.className = 'book-item';
bookItem.textContent = book.title;
bookItem.dataset.id = book.id;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.onclick = () => deleteBook(book.id);
bookItem.appendChild(deleteButton);
bookList.appendChild(bookItem);
});
}
async function addBook() {
const title = document.getElementById('book-title').value;
if (!title) {
alert('Please enter a book title.');
return;
}
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title })
});
const newBook = await response.json();
fetchBooks();
document.getElementById('book-title').value = '';
} catch (error) {
console.error('Error adding book:', error);
}
}
async function deleteBook(id) {
try {
await fetch(`${API_URL}/${id}`, {
method: 'DELETE'
});
fetchBooks();
} catch (error) {
console.error('Error deleting book:', error);
}
}
Explanation of the JavaScript Code
Fetching Books: The fetchBooks method shows the books on the page after retrieving the list from the backend server. It sends a GET request to the /books endpoint using the retrieve API, and then it calls displayBooks to handle the response.
Books Displayed: Using the list of books as input, the displayBooks method generates HTML elements for each book, along with a remove button. The book-list container has each book object attached to it.
Adding a Book: To add a new book, the addBook method sends a POST request to the /books endpoint after reading the book title from the input field. If it is successful, the input field is cleared and the most recent list of books is retrieved.
Removing a Book: To remove a specific book, use the deleteBook method to make a DELETE request to the /books/:id endpoint. It retrieves the most recent list of books if it is successful.
Step 4: Running the Application
To run this application, you’ll need a server to serve the index.html
and app.js
files. You can use a simple HTTP server like http-server
or live-server
. Here are the steps to set up and run the application:
Open the application in a browser:
Install http-server
:
npm install -g http-server
Navigate to the project directory:
cd path/to/your/project
Start the server:
http-server
Open the application in a browser:
http://localhost:8080
Now, you should see the Book Manager application in your browser. You can add new books and delete existing ones, with all operations being handled via HTTP requests to the backend service.
HTTP communication with backend services is a basic component of contemporary web development. You may create reliable and interactive online apps by learning about HTTP methods and status codes and knowing how to apply them in your projects. This blog post gives an example of how to use HTTP to carry out CRUD tasks, which are frequently used in online applications.