1. javascript
  2. /advanced
  3. /working-with-apis

Understanding APIs

Getting Started

Have you ever wondered how apps like Spotify can access millions of songs? How services like GIPHY spoils us with an endless stream of gifs? A big part of the answer lies in APIs.

APIs(Application Programming Interfaces) were present before the makings of the modern web. At their core, they represent a blueprint for the way that distinct software applications communicate. We'll be mostly focusing on their modern-day usage related to the web and how they've opened up a plethora of possibilities for developers.

What are APIs?

APIs enable different applications to communicate with each other, exchanging both data and functionality. A good example of this is a stock market app that accesses real-time stock prices by "speaking" to a financial data provider.

Today, there are exhaustive options for APIs in terms of their specification. But, we'll just briefly mention REST APIs, as something you'll likely encounter, and WebSockets, as an entirely different approach.

REST APIs use the HTTP protocol to access and manipulate data. When we make a request to a REST API, we typically specify an endpoint (a specific location of data) and an HTTP method (such as GET, POST, PUT, or DELETE). Then, the API responds with an HTTP response, including a status code and any data that we requested.

WebSockets, on the other hand, provide a persistent connection between the client and server, enabling real-time data transfer that goes in both directions.

HTTP Methods

HTTP, or the Hypertext Transfer Protocol, functions as the foundation of web communication. It grants clients and servers an exchange of information and performs actions through a request-response protocol.

These methods are in a way verbs, that define the action i.e. the type of request being made by the client. Below, you can observe a brief overview of each method.

  • GET: Retrieves data from the specified endpoint;

  • POST: Submits data to the specified endpoint;

  • PUT: Updates data at the specified endpoint;

  • DELETE: Deletes data from the specified endpoint;

  • PATCH: Partially updates data at the specified endpoint.

The XMLHttpRequest Request

Before the introduction of the fetch method, XMLHttpRequest (often abbreviated as xhr) was the primary means of performing HTTP requests in JavaScript. With xhr, we can send HTTP requests to retrieve data from a server and update the content of a page without having to reload the entire page. Logically, AJAX or (Asynchronous JavaScript And XML) programming makes extensive use of the XMLHttpRequest.

// Example of an asynchronous xhr request
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.send();

The async property of the xhr object is set to true, which makes the request asynchronous. Next, the onreadystatechange event handler is still used to check the status of the request and process the response from the server, but the rest of the code continues to execute while the request is being processed.

Fetch as a Modern Alternative

In recent years, Fetch became the preferred option to XHR as it gives us a cleaner API for performing HTTP requests. It returns a Promise that resolves to the response of the request, allowing you to handle the response using async/await or with a .then chain.

fetch('https://api.example.com/data')
  .then(response => {
    // Parse the response into a JSON object
    return response.json();
  })
  .then(data => {
    // Log the data to the console
    console.log(data);
  })
  .catch(error => {
    // Log the error to the console
    console.error(error);
  });

Understand async/await functions in more detail, and take a look at a mock example of a POST method used with a fetch for handling user registration and login.

HTTP Response Codes

HTTP response codes are digits that indicate the outcome of an HTTP request. In modern websites, we might see them alongside friendly messaging and illustrations, created to ease the frustration of a user.

But as developers, understanding these codes is crucial when working with APIs, as they provide insight into the status of the request and any potential errors that might arise.

Some of the most common response codes include:

  • 200 OK: The request was successful

  • 201 Created: The request was successful, and a resource was created

  • 204 No Content: The request was successful, but there is no representation to return (i.e. the response is empty)

  • 400 Bad Request: The request could not be understood or was missing required parameters

  • 401 Unauthorized: Authentication failed or user does not have permissions for the requested operation

  • 403 Forbidden: Authentication succeeded, but the authenticated user does not have access to the requested resource

  • 404 Not Found: The requested resource could not be found

  • 500 Internal Server Error: An error occurred on the server

Using & Accessing APIs

In today's market, it's common for companies to offer both open-source access and paid APIs, providing developers with flexibility and options depending on their project's requirements. These providers generally include in-depth documentation with detailed guidelines to help ensure a smooth integration process.

APIs have a broad range of use cases, such as retrieving data from external sources like weather, stock prices, or news articles. Moreover, they can enhance a project's capabilities by adding advanced functionality such as image recognition. APIs can also integrate with third-party services, including social media, payment gateways, email services, and more.

Final Thoughts

While web development can be a mouthful of abbreviations and terminology, at its core, it's about connecting different functionalities and making it possible for them to communicate. With APIs, we've added another layer of readability and made it easier to work with external data and services.

Useful Resources

List of HTTP status codes.