Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Learning

Integrating with APIs: A beginner's guide for front-end developers

Integrating with APIs is something every professional front-end developer will do at some point. In this article, Hikmah outlines the main concepts.

Hikmah Yousuph

·

13 Mar 2024

When you interact with a website, mobile app, or any digital service, a lot is happening behind the scenes to process the data you requested through the application. For this to happen, different pieces of software need to share information successfully.

In this article, we'll explore Application Programming Interfaces (APIs), the different types of APIs you'd encounter as a developer, and some real-world examples of working with APIs. Let's get started!

What is an API?

An API is a set of rules that allows different applications to communicate with each other. Depending on the API's type and the communication methods it enables, information can be shared easily.

Developers can use APIs to access databases, send and retrieve data, and update information, among other things. We use APIs in our daily lives, like logging into a website with our social media accounts, submitting a form, using the weather app, etc.

Integrating an API on the front-end means getting information from a server and using it in the user interface, enabling real-time data retrieval and creating dynamic user experiences. However, not all APIs are limited to these as they have various functions and usage. Some APIs may focus on data storage, task automation, authentication, and more.

To use an API effectively, it is essential to have an in-depth understanding of the documentation provided. This documentation outlines important details such as endpoints, data formats, and authentication methods, ensuring a successful implementation.

Types of API

There are many kinds of API, but let’s look at the ones you are likely to come across as a beginner:

  1. HTTP APIs:  HTTP APIs are a broad category that can be accessed over the web using the HTTP protocol. They encompass various protocols for communication between web servers and clients.
  2. REST (Representational State Transfer, or RESTful API): An architectural style for designing networked applications. It is the most commonly used API and a subset of HTTP APIs that uses a specific structure of request methods and URLs for communication and often uses JSON as the data format.
  3. Third-party SDKs: External software development kits that can be integrated into your applications. These kits provide functionality or data that developers can leverage, sparing them from reinventing the functionalities. Examples include social media SDKs (like logging in with Facebook or Google), payment gateways, weather data, etc.

In this article, I'll focus on HTTP APIs and how you might interact with them as a front-end developer.

Diagram of how a HTTP API works, showing the client making a HTTP request to the server, which responds with JSON data.

HTTP APIs outline a server's available endpoints. An endpoint is a specific URL you can request to perform a particular action or retrieve specific data. These endpoints can be requested with various methods (POST, GET, PUT, DELETE, etc.) and URLs made available by the API.

Unlike other servers that respond with HTML, which is suitable primarily for rendering web pages in browsers, HTTP APIs respond with data, usually in the form of JSON or, in some cases, XML. Because of this, HTTP APIs are powerful as they can be consumed by web browsers, mobile apps, command line interfaces, etc.

Working with JSON data

Introduction to JSON

The response data from APIs can be in various formats, but one of the most used is JSON (JavaScript Object Notation). JSON is a lightweight text-based format for representing data. It is very similar to JavaScript Object syntax, containing key-value pairs in objects.

While JSON is very popular, you may encounter other data formats. However, JSON has gained widespread preference due to its concise syntax and ease of parsing. JSON's lightweight structure reduces data size and parsing complexities, enhancing efficiency in data transfer over the network.

Parsing JSON data

Understanding how to parse JSON data is an important skill for front-end developers working with APIs or any form of external data. Parsing involves converting a JSON string into a usable JavaScript object. Let's take a look at a Frontend Mentor challenge which provides us with a data.json file:

[
  {
    "category": "Reaction",
    "score": 80,
    "icon": "./images/icon-reaction.svg",
    "color": "0, 100%, 67%"
  },
  {
    "category": "Memory",
    "score": 92,
    "icon": "./images/icon-memory.svg",
    "color": "39, 100%, 56%"
  },
  {
    "category": "Verbal",
    "score": 61,
    "icon": "./images/icon-verbal.svg",
    "color": "166, 100%, 37%"
  },
  {
    "category": "Visual",
    "score": 72,
    "icon": "./images/icon-visual.svg",
    "color": "234, 85%, 45%"
  }
]

You’ll need to import this in a JavaScript file to parse and use this data. If the data is not parsed and you attempt to use it as a JavaScript object, you will likely encounter a SyntaxError. The reason is that JSON is a string representation of data, and JavaScript objects are not the same as JSON strings. The JSON.parse() method in JavaScript is used for parsing JSON data, which is a string format that differentiates it from JavaScript objects. This method takes a JSON string as input and returns a JavaScript object to be used in the client UI.

data.forEach(item => `
  ...

  <div class="summary-item" style="color: hsl(${item.color})">
    <div class="left">  
      <img class="icon" src="${item.icon}" alt="${item.category} Icon" />
      <p class="category">${item.category}</p>
    </div>
    <p class="summary-score">
      <span class="score">${item.score}</span> / 100
    </p>
  </div>

  ...
`);

Using build tools like Webpack or libraries like Axios to handle JSON data, as well as the native fetch API in modern browsers, there is no need to explicitly use JSON.parse(). These tools handle the parsing of JSON responses automatically, simplifying the development process for front-end developers.

As we progress, we will look at how to make a request and fetch data.

API requests

Making requests to HTTP APIs involves making a call to an endpoint and expecting a response back. An endpoint is a URL that provides access to specific functionalities.

HTTP methods and requests

There are four common HTTP methods:

  • GET: Retrieve data from a specific resource.

  • POST: Submit data to be processed to a specified resource, e.g., add a new user, post, etc.

  • PUT: Update existing data on the server.

  • DELETE: Remove specific data from the server.

These methods can simply be grouped as CRUD operations. CRUD stands for Create, Read, Update, and Delete.

Example of making an API request

When integrating an API into your application, you need to know why you want to use a specific API. Is it to display countries and their details on an interface you built? Or shorten any URL easily? Or generate random facts?

Let's examine another Frontend Mentor challenge that includes pulling data from a third-party API: the Advice Slip API, which generates random advice quotes.

Documentation is provided to guide you through using every third-party API. Although all APIs have a format for requesting and receiving a response, each API offers different endpoints that return data in different structures.

Screenshot of the Advice Slip API homepage.

Once the API endpoint provided, https://api.adviceslip.com/advice, is hit, the server sends a response that includes the JSON data.

The data returned each time the endpoint is hit would look something like this:

{"slip": { "id": 129, "advice": "Stop procrastinating."}}

Similar to the JSON file example, the data is returned in JSON format and can then be used to populate the client code.

...
const getAdvice = () => {
  adviceElement.innerHTML = "<p>Loading...</p>";

  fetch("https://api.adviceslip.com/advice")
    .then(response => response.json())
    .then(data => {
      adviceElement.innerHTML = `
        <h2>Advice number ${data.slip.id}</h2>
        <blockquote>"${data.slip.advice}"</blockquote>
      `;
    })
    .catch(err => {
      adviceElement.innerHTML = `
          <p>${err.message}.</p>
      `;
    });
};

newAdviceBtn.addEventListener("click", getAdvice);

// Initial advice retrieval
getAdvice();
});
...

The code above shows how to make a request to the Advice Slip API using the fetch() method. After that, it proceeds with a series of actions: first, it converts the response JSON to a JavaScript object using the .json() method, then it sets the contents of a DOM node with data extracted from the JavaScript object. If any errors occur in these steps, an error message will be set instead. By ensuring that adviceElement has an aria-live=”polite” set, assistive technologies will announce the change to the user.

Handling API responses

API responses are returned after making requests. Responses include status codes that indicate the success or failure of a request. Here are some common HTTP status codes:

  • 200 (OK): The request was successful.

  • 201 (Created): A new resource was successfully created.

  • 400 (Bad Request): The server cannot process the request due to invalid syntax or missing parameters.

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

  • 422 (Unprocessable Entity): The server understands the content type of the request entity but was unable to process the request.

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

Error handling

Usually, a specific response is expected to return when a request is made to an API. However, there are cases where this doesn’t go as planned, and instead of the expected data, an error response is returned. This can happen due to various reasons, such as network issues, server errors, or incorrect request parameters.

HTTP status codes in the range of 400 to 599 are used to indicate errors. To handle any of these errors, .catch() method is used. With this method, we can catch any errors during the API request and respond accordingly. Let's take a look at how error handling is implemented in the code snippet from our previous example:

...
.catch(err => {
  adviceElement.innerHTML = `
      <p>${err.message}.</p>
  `;
});
...

Within the .catch() block, the adviceElement is updated to display an error message to the user. The API provides this error message along with additional information about the encountered error. By dynamically updating the code to display the error message, users are informed about the specific issue that occurred during the API request process.

Conclusion

Understanding APIs and their integration gets easier once you build out applications with them. Get comfortable using JSON data in your application, and using APIs becomes easier. To get a better hang of APIs, be sure to try out these Frontend Mentor Challenges:

As you begin your journey integrating APIs, ensure that you always follow the provided documentation. Understanding the API through its documentation is the key to using it. Without a clear comprehension of the documentation, developers may encounter challenges implementing APIs into their applications.

Practice, research, and continuous learning are what you need to master API integration for front-end developers. Be curious, and immerse yourself in practical challenges to solidify your understanding. Before you know it, you'll confidently navigate any API and use it effortlessly in your projects.

Practice building projects like a pro

  • Portfolio-ready projects
  • Professional design files
  • Curate your profile
  • Unlimited solution refinement
Unlock Pro

Get all community news and our latest articles in your inbox

Join over 50,000 developers receiving updates via our newsletter. Stay up-to-date with new challenges, articles, community news, featured solutions, and handy links from across the web. We promise no spam, and you can unsubscribe at any time.