Skip to main content

Command Palette

Search for a command to run...

Working With API's : A Comprehensive Guide

Updated
7 min read
Working With API's : A Comprehensive Guide
V

I'm developer and technical writer passionate about creating exceptional software solutions and crafting engaging technical content. With a strong background in software development and a flair for effective communication, I bring a unique blend of technical expertise and writing skills to my work.

Introduction

API stands for "Application Programming Interface."It's a set of rules, protocols, and tools that allow different software applications to communicate and interact with each other. APIs are widely used to enable the integration of different systems, allowing them to work together and provide enhanced functionality to users.

For example, A website allows users to share articles on Twitter. When a user clicks the "Tweet" button, the website uses the Twitter API to post the article link to the user's Twitter feed, allowing them to share it with their followers. Understanding how to work with APIs is a key skill for any developer. In this article which is Part 2 of the series, you will learn how to work with an API.

pre-requisite

Importance Of API in web development

  1. APIs enable web applications to access and integrate data from various sources, enhancing content richness and dynamism.

  2. APIs allow developers to extend their web applications' functionality by integrating third-party services, libraries, or plugins.

  3. APIs facilitate communication and data exchange between different platforms, ensuring broad compatibility and reach.

Types of API

There are different types of API, each tailored to specific use cases and scenario

  • RESTFUL API

  • graphQL API

  • SOAP API and so on.

Examples of API

  • GoogleMaps API

  • Unsplash API

  • OpenWeather API and so on.

API protocols

API protocols refer to the communication protocols and data formats used to exchange data between a client and a server when making API requests. These protocols define the rules for how data is formatted, transmitted, and received.API has several protocols but in this article, we will be focusing on HTTP/HTTPS, which is widely used for web APIs.

HTTP methods (or HTTP request methods) are standardized verbs that define the action a client (typically a web browser or application) should perform when requesting a web server. Each HTTP method corresponds to a specific action, and it determines how the server should handle the request. Here are some common HTTP methods :

  1. GET: This method is used to retrieve data from the server.

  2. POST: is used to submit data to the server for processing.

  3. PUT: is used to update a resource or create it if it doesn't exist.

  4. DELETE: DELETE is used to request the removal of a resource from the server.

  5. PATCH: is used to apply partial modifications to a resource.

  6. HEAD: Similar to GET, a HEAD request asks the server to provide metadata about a resource without actually sending the resource's data.

HTTP Response status codes:

In HTTP, several status codes indicate the outcome of an HTTP request-response cycle.

  1. 200: OK (successful)

  2. 404: Not Found

  3. 301: Moved permanently

  4. 403: Forbidden and so on.

API endpoints

An endpoint is a specific URL that represents a particular resource provided by an API. It serves as the entry point through which clients (such as web applications, mobile apps, or other software) can access the functionalities and data offered by the API.

Example of API Endpoint:

Let's consider the Unsplash API, which provides access to a vast collection of high-quality images. An example API endpoint for retrieving a list of photos might look like this:

https://api.unsplash.com/photos

In this example:

  • https://api.unsplash.com is the base URL of the Unsplash API.

  • /photos is the route or path that represents the collection of photos.

Making API requests

Traditional XMLHttpRequest Approach

Traditionally, before modern JavaScript libraries like Fetch and Axios became prevalent, developers used a combination of JavaScript's built-in XMLHttpRequest object and callback functions to make HTTP requests. Here's a basic example of how this traditional method worked:

// Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();

// Configure the request: specify the HTTP method (GET, POST, etc.) and the URL
xhr.open('GET', 'https://api.unsplash.com/photos', true);

// Set up a callback function to handle the response when it arrives
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    // Request was successful; process the response
    var responseData = JSON.parse(xhr.responseText);
    console.log(responseData);
  } else {
    // Request encountered an error
    console.error('Request failed with status:', xhr.status);
  }
};
// Set up a callback for network errors
xhr.onerror = function () {
  console.error('Network error occurred');
};
// Send the request
xhr.send();

In this example:

  1. An XMLHttpRequest object is created.

  2. The request is configured with the HTTP method, URL, and whether it should be asynchronous (true in this case).

  3. Callback functions (xhr.onload and xhr.onerror) are defined to handle the response and network errors.

  4. Finally, the request is sent with xhr.send().

While this method is functional, it can be less user-friendly and less convenient than modern approaches like Fetch or Axios. These modern methods simplify request handling and provide better support for Promises and async/await, making asynchronous operations and error handling more straightforward.

THE FETCH API

The Fetch API is a modern JavaScript API for making HTTP requests to fetch resources (like data or files) from web servers. It provides a more flexible and promise-based approach compared to the older XMLHttpRequest (XHR) method.

Let's modify the API request with fetch()

// Using Fetch to make an API request
fetch('https://api.unsplash.com/photos')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

Here's how Fetch works:

  • To send an HTTP request using Fetch, you use the fetch() function, passing in the URL you want to request as the first argument.

  • This function returns a Promise that resolves to the Response object representing the response to the request. You can then use promise-based syntax to handle the response.

  • Once the request is made, you can use .then() and .catch() methods on the Promise to handle the response.

  • The response object contains information about the response, including the status, headers, and body. You can access the response data by calling methods like .json(), .text(), or .blob() on the response object.

Here's the same code using the async/await syntax for cleaner and more readable code:

// Define an asynchronous function to fetch data
async function fetchData() {
  try {
    // Send a GET request to the specified API endpoint (Unsplash API in this case)
    const response = await fetch('https://api.unsplash.com/photos');

    // Check if the response status is within the 200-299 range (indicating a successful response)
    if (response.ok) {
      // Parse the response body as JSON
      const data = await response.json();

      // Log the retrieved data to the console
      console.log(data);
    } else {
      // Log an error message if the network response is not okay
      console.error('Network response was not ok');
    }
  } catch (error) {
    // Catch and handle any errors that occur during the fetch operation
    console.error('Fetch error:', error);
  }
}

// Call the fetchData function to initiate the data retrieval process
fetchData();

AXIOS

Axios is a popular JavaScript library for making HTTP requests, including API requests. It provides a clean and easy-to-use API for sending HTTP requests and handling responses.

Installing AXIOS

To install Axios, use either npm or yarn. Open your terminal and run one of the following commands:

  • For npm: npm install axios

  • For yarn: yarn add axios

Here's the same code using Axios

import axios from 'axios';

async function fetchData() {
  try {
    const response = await axios.get('https://api.unsplash.com/photos');
    console.log(response.data);
  } catch (error) {
    console.error('Axios error:', error);
  }
}
fetchData();

In this code:

  1. We use import axios from 'axios'; to import the Axios library.

  2. We define an async function named fetchData() to make the API request.

  3. Inside the try block, we use await to make the GET request to the API endpoint and store the response in the response variable.

  4. We then log the data from the API response using console.log(response.data); if the request is successful.

  5. If the request encounters any issues, we catch the error using the catch block and log it with console.error('Axios error:', error);.

  6. Finally, we call the fetchData() function to execute the API request.

This may seem like a lot, but let's transition to Part 3 where we'll bring all this knowledge into action by building our photo app using the Unsplash API. Get ready to witness everything we've learned in practice!