APIs Decoded: What They Are and How to Use Them in JavaScript

VANSH KANSALVANSH KANSAL
4 min read

In today’s world of web development, APIs are everywhere. Whether you’re fetching data from a weather service, posting comments to a blog, or integrating payment processing, you’re almost certainly interacting with APIs behind the scenes.

This post will break down what APIs are, why they matter, and how you can work with them in JavaScript using fetch and async/await.


What is an API?

API stands for Application Programming Interface.

Put simply, it’s a set of rules and protocols that allow two software applications to talk to each other.

Imagine APIs as menus in a restaurant:

  • The menu lists the dishes (operations) you can order.

  • You tell the waiter (the API) what you want.

  • The kitchen (the server) prepares it and returns it to you.

An API defines:

  • What you can request (endpoints and methods)

  • How you must request it (data format, headers, authentication)

  • What you get back (usually JSON or XML)


Types of APIs

Though there are many types, the most common for web development are REST APIs:

  • REST: Representational State Transfer

  • Use HTTP methods (GET, POST, PUT, DELETE)

  • Data typically exchanged in JSON format

Other types include:

  • GraphQL: A query language for APIs

  • WebSockets: For real-time, two-way communication

In this Blog, we’ll focus on REST APIs with JSON because they are the most used.


Making API Requests in JavaScript

JavaScript in the browser gives you several tools to call APIs.
Today, the most modern and widely used approach is fetch(), which returns a Promise.

Let’s break it down step by step.


Example 1: Basic Fetch Request

Suppose you want to get data from a placeholder API:

fetch('https://mywebsite.com/posts/1')
  .then(response => response.json()) // Parse JSON from the response
  .then(data => console.log(data))   // Do something with the data
  .catch(error => console.error('Error fetching data:', error));

How this works:

  1. fetch() makes an HTTP GET request to the URL.

  2. It returns a Promise that resolves to a Response object.

  3. response.json() reads and parses the body as JSON.

  4. The parsed data is available in the next .then().


Another Way : Using async / await for Cleaner Syntax

What is async / await?

async keyword

Adding async before a function does two things:

  • It always returns a Promise.

  • It allows you to use await inside.

await keyword

await can only be used inside an async function.
It pauses the function execution until the Promise resolves, and then returns the result.

Think of await as saying: "Wait here until I get the value, then keep going."

While chaining .then() works fine, async/await makes your code more readable:

async function fetchPost() {
  try {
    const response = await fetch('https://mywebsite.com/posts/1');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchPost();

What happens here:

  • The async keyword allows await inside the function.

  • await fetch() waits for the network request.

  • We check response.ok to handle HTTP errors.

  • await response.json() parses the body.

  • Errors are caught in the catch block.


Example 2: Making a POST Request (sending data through API )

Fetching data is one thing, but APIs often need you to send data too.
Here’s how you can POST JSON:

async function createPost() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: 'My New Post',
        body: 'This is the content of the post.',
        userId: 1,
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Created post:', data);
  } catch (error) {
    console.error('Error creating post:', error);
  }
}

createPost();

Notes:

  • method: 'POST' specifies the HTTP method.

  • headers include Content-Type so the server knows you’re sending JSON.

  • body is stringified JSON data.


Best Practices for Working with APIs

Always handle errors
Check response.ok and wrap in try/catch.

Use async/await for clarity
Helps avoid callback hell and makes error handling easier.

Validate data
Don’t assume the API always returns what you expect.

Respect rate limits
APIs may throttle you if you make too many requests.

Secure your API keys
Never expose sensitive credentials in frontend JavaScript.


TL;DR

APIs are the backbone of modern web apps.
Mastering fetch and async/await gives you the tools to build powerful, dynamic applications.

Whether you’re:

  • Loading data dynamically

  • Submitting forms

  • Integrating third-party services

Happy coding!

10
Subscribe to my newsletter

Read articles from VANSH KANSAL directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

VANSH KANSAL
VANSH KANSAL