API Server Example

Let's explore a Customer Management API capable of retrieving customer data, adding new customers, updating existing customer information, and deleting customers from the server. Now, we'll delve into the mechanisms through which the API accomplishes these functionalities.

Retrieving customer data

The following code will send a request to serve for retrieving customer information from the database,

fetch('/api/books')
    .then(response => response.json())
    .then(data => {
      console.log('List of Books:', data);
    })
    .catch(error => console.error('Error fetching books:', error));

Explanation:

  1. fetch('/api/books'): Initiates a GET request to the '/api/books' endpoint. The fetch function is a built-in JavaScript function used to make HTTP requests.

  2. .then(response => response.json()): Converts the response body to JSON format. The response.json() method returns a promise that resolves with the JSON representation of the response body.

  3. .then(data => { ... }): Handles the JSON data received from the server. In this block of code, the list of books is logged to the console using console.log().

  4. .catch(error => console.error('Error fetching books:', error)): Catches any errors that may occur during the fetch operation. If an error occurs, it logs an error message to the console using console.error().

Adding new customers

The code shared below will add new customers to the database.

 fetch('/api/books', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(bookData),
  })
    .then(response => response.json())
    .then(data => {
      console.log('New Book Created:', data);
    })
    .catch(error => console.error('Error creating book:', error));

Explanation:

  1. fetch('/api/books', { ... }): Initiates a POST request to the '/api/books' endpoint with additional options provided in the second parameter, including the HTTP method, headers, and request body.

  2. method: 'POST': Sets the HTTP method of the request to POST, indicating that a new resource (book) should be created on the server.

  3. headers: { 'Content-Type': 'application/json' }: Specifies the content type of the request payload as JSON. This informs the server that the body of the request contains JSON-formatted data.

  4. body: JSON.stringify(bookData): Converts the JavaScript object bookData into a JSON string using JSON.stringify() and sends it as the body of the POST request. bookData likely contains information about the new book being created.

  5. .then(response => response.json()): Parses the response from the server as JSON once it's received.

  6. .then(data => { ... }): Handles the JSON data received from the server. In this block of code, the newly created book data is logged to the console using console.log().

  7. .catch(error => console.error('Error creating book:', error)): Catches any errors that may occur during the fetch operation. If an error occurs, it logs an error message to the console using console.error().

Updating existing customer information

Take a look at the below code. It'll update the existing customer data,

 fetch(`/api/books/${bookId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(updatedBookData),
  })
    .then(response => response.json())
    .then(data => {
      console.log('Book Updated:', data);
    })
    .catch(error => console.error('Error updating book:', error));

Explanation:

  1. fetch('/api/customers/123', { ... }): Initiates a PUT request to the '/api/customers/123' endpoint with additional options provided in the second parameter, including the HTTP method, headers, and request body. The '/123' part of the URL likely represents the unique identifier of the customer being updated.

  2. method: 'PUT': Sets the HTTP method of the request to PUT, indicating that the existing resource (customer data) with the specified identifier should be updated on the server.

  3. headers: { 'Content-Type': 'application/json' }: Specifies the content type of the request payload as JSON. This informs the server that the body of the request contains JSON-formatted data.

  4. body: JSON.stringify(updatedCustomerData): Converts the JavaScript object updatedCustomerData into a JSON string using JSON.stringify() and sends it as the body of the PUT request. updatedCustomerData likely contains the updated information about the customer.

  5. .then(response => response.json()): Parses the response from the server as JSON once it's received.

  6. .then(data => { ... }): Handles the JSON data received from the server. In this block of code, the updated customer data is logged to the console using console.log().

  7. .catch(error => console.error('Error updating customer data:', error)): Catches any errors that may occur during the fetch operation. If an error occurs, it logs an error message to the console using console.error().

Deleting customers

To remove an existing customer follow the below code,

 fetch(`/api/books/${bookId}`, {
    method: 'DELETE',
  })
    .then(response => response.text())
    .then(data => {
      console.log(data);
    })
    .catch(error => console.error('Error deleting book:', error));

Explanation:

  1. fetch(/api/books/${bookId}, { ... }): Initiates a DELETE request to the '/api/books/{bookId}' endpoint, where {bookId} is likely a placeholder for the unique identifier of the book to be deleted. The backticks (`) are used for string interpolation to dynamically construct the URL.

  2. method: 'DELETE': Sets the HTTP method of the request to DELETE, indicating that the resource (book) with the specified identifier should be deleted from the server.

  3. .then(response => response.text()): Converts the response body to text once it's received. In a DELETE request, there might not be a JSON response body, so converting it to text allows for easier handling.

  4. .then(data => { ... }): Handles the response data received from the server. In this block of code, the response data (likely a confirmation message) is logged to the console using console.log().

  5. .catch(error => console.error('Error deleting book:', error)): Catches any errors that may occur during the fetch operation. If an error occurs, it logs an error message to the console using console.error().