📌 What is API Integration?

API (Application Programming Interface) integration allows different software applications to communicate.

For example:

  • A frontend app (React, Next.js) fetches data from a backend API (NestJS, Express, Django, .NET).
  • A backend API connects to a database (MongoDB, PostgreSQL) or another external API (OpenAI, Stripe).

Simple Example:

🔹 You visit a weather app → It sends a request to a weather API → API responds with the weather data → The app displays it.


Absolutely! Let's dive deeper into API requests & responses and handling authentication (API Keys, JWT) with detailed explanations and hands-on examples for beginners. 🚀


🟢 Step 1: Understanding API Requests & Responses

An API request is how we ask a server for data, and an API response is how the server replies with the requested data.

📌 1.1 Components of an API Request

An API request typically has the following parts:

1️⃣ HTTP Method → Defines the type of operation (GET, POST, PUT, DELETE).

2️⃣ API Endpoint (URL) → The address of the API we’re calling.

3️⃣ Headers → Extra information (like authentication, content type).

4️⃣ Body (optional) → Data sent with the request (for POST, PUT).


🔹 Example: Sending a GET Request

A GET request retrieves data from an API.

📝 Request Example:

🔹 URL: https://jsonplaceholder.typicode.com/posts/1

🔹 Method: GET

🔹 Headers: None required

🔹 Body: Not needed

🖥️ JavaScript (Fetch API) Example:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json()) // Convert response to JSON
  .then(data => console.log(data)) // Log the response
  .catch(error => console.error("Error fetching data:", error));

🔹 Expected API Response:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit..."
}

We successfully retrieved a blog post from the API.


🔹 Example: Sending a POST Request

A POST request is used to send data to an API.

📝 Request Example:

🔹 URL: https://jsonplaceholder.typicode.com/posts

🔹 Method: POST

🔹 Headers: { "Content-Type": "application/json" }

🔹 Body:

{
  "title": "New Post",
  "body": "This is the post content",
  "userId": 1
}

🖥️ JavaScript (Fetch API) Example:

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    title: "New Post",
    body: "This is the post content",
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log("Created Post:", data))
  .catch(error => console.error("Error:", error));

🔹 Expected API Response (confirmation of post creation):

{
  "title": "New Post",
  "body": "This is the post content",
  "userId": 1,
  "id": 101
}

The server responded with the newly created post (ID: 101).


🟡 Status Codes in API Responses

When an API responds, it returns an HTTP status code to indicate success or failure.

Common status codes:

  • 200 OK – Request successful
  • 201 Created – Data was created (POST request success)
  • 400 Bad Request – The request was incorrect
  • 401 Unauthorized – API key or token is missing/invalid
  • 403 Forbidden – You don't have permission
  • 404 Not Found – Resource doesn’t exist

📌 Example of checking the status code before using the response:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log("Post:", data))
  .catch(error => console.error("Error fetching post:", error));

✅ Now, we have a better understanding of API requests & responses! 🎯


🟢 Part 2: Handling API Authentication

When integrating with APIs, you often need authentication to access restricted resources.


📌 2.1 API Keys Authentication

An API key is like a password that allows access to an API.

🔹 Example: OpenWeather API

🔹 URL:

https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY

🖥️ JavaScript (Fetch API) Example:

const API_KEY = "your_api_key_here"; // Replace with your API key
fetch(`https://api.openweathermap.org/data/2.5/weather?q=London&appid=${API_KEY}`)
  .then(response => response.json())
  .then(data => console.log("Weather Data:", data))
  .catch(error => console.error("Error fetching weather data:", error));

✅ The API will return weather details if the API key is valid.


📌 2.2 JWT (JSON Web Token) Authentication

JWT is commonly used for secure user authentication.

🔹 How JWT Works

1️⃣ User logs in with email & password.

2️⃣ Server generates a JWT token and sends it to the user.

3️⃣ User includes this JWT token in every API request.

4️⃣ Server verifies the token before responding.

🔹 Example: User Login with JWT

Assume we have a backend API at https://api.example.com/login.

🖥️ JavaScript (Fetch API) Example:

fetch("https://api.example.com/login", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    email: "[email protected]",
    password: "password123"
  })
})
  .then(response => response.json())
  .then(data => {
    console.log("Login successful, JWT token:", data.token);
  })
  .catch(error => console.error("Error logging in:", error));

✅ The server responds with:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5..."
}

This JWT token is used to access protected APIs.


📌 2.3 Using JWT for API Requests

Once we have the JWT token, we include it in the Authorization header.

🔹 Example: Fetching User Profile with JWT

const jwtToken = "your_jwt_token_here"; // Get this from login response

fetch("https://api.example.com/profile", {
  method: "GET",
  headers: {
    "Authorization": `Bearer ${jwtToken}`
  }
})
  .then(response => response.json())
  .then(data => console.log("User Profile:", data))
  .catch(error => console.error("Error fetching profile:", error));

✅ If the token is valid, the server will return user details.

✅ If the token is missing or invalid, the API will return 401 Unauthorized.


🎯 Summary

API Requests & Responses

  • Use GET, POST, PUT, DELETE methods
  • Understand status codes (200, 201, 401, 404)
  • Learn to handle errors properly

Handling Authentication

  • API Keys → Simple authentication (used in OpenWeather, Google Maps)
  • JWT Tokens → Secure authentication (used for login systems)

🟢 Step 2: Using API in Frontend (React Example)

Let’s build a simple React component to fetch and display Pokémon details.

📌 2.1 React Component Example

import { useState, useEffect } from "react";

function PokemonInfo() {
  const [pokemon, setPokemon] = useState(null);

  useEffect(() => {
    fetch("https://pokeapi.co/api/v2/pokemon/pikachu")
      .then(response => response.json())
      .then(data => setPokemon(data))
      .catch(error => console.error("Error fetching data:", error));
  }, []);

  return (
    <div>
      {pokemon ? (
        <div>
          <h2>{pokemon.name.toUpperCase()}h2>
          <p>Height: {pokemon.height}p>
          <p>Weight: {pokemon.weight}p>
          <p>Abilities:p>
          <ul>
            {pokemon.abilities.map((a, index) => (
              <li key={index}>{a.ability.name}li>
            ))}
          ul>
        div>
      ) : (
        <p>Loading...p>
      )}
    div>
  );
}

export default PokemonInfo;

What’s happening here?

  • We fetch data when the component loads.
  • We update the state with the Pokémon details.
  • We display the name, height, weight, and abilities in a simple UI.

🟢 Step 3: Using API in Backend (NestJS Example)

Let’s say we are building our own backend API using NestJS.

📌 3.1 NestJS Controller Example

Create a simple NestJS API that returns a list of users.

import { Controller, Get } from "@nestjs/common";

@Controller("users")
export class UsersController {
  @Get()
  getUsers() {
    return [
      { id: 1, name: "John Doe", email: "[email protected]" },
      { id: 2, name: "Jane Doe", email: "[email protected]" }
    ];
  }
}

🔹 If you visit http://localhost:3000/users, the API will return:

[
  { "id": 1, "name": "John Doe", "email": "[email protected]" },
  { "id": 2, "name": "Jane Doe", "email": "[email protected]" }
]

Now, our frontend can fetch this user data and display it.


🟢 Step 4: Handling API Authentication With Weather app

Some APIs require authentication (login access). The most common methods:

1️⃣ API Keys → Example: OpenWeather API

2️⃣ OAuth 2.0 → Example: Google, Facebook Login

3️⃣ JWT (JSON Web Tokens) → Used for secure user authentication

📌 4.1 Example: Using API Key in Fetch Request

fetch("https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error fetching data:", error));

What’s happening here?

  • We send a request to OpenWeather API with an API Key.
  • API returns weather details for London.

🟢 Step 5: Testing APIs using Postman

📌 5.1 Steps to Test an API in Postman

1️⃣ Open Postman.

2️⃣ Enter the API URL (e.g., http://localhost:3000/users).

3️⃣ Click Send.

4️⃣ View the response.

Postman allows us to test, debug, and automate API requests before integrating them into our app.


🟢 Step 6: Handling Errors in API Calls

📌 6.1 Example: Handling Errors in JavaScript

fetch("https://pokeapi.co/api/v2/pokemon/wrongname")
  .then(response => {
    if (!response.ok) {
      throw new Error("Pokémon not found");
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error.message));

✅ If the Pokémon name is wrong, we display "Pokémon not found" instead of crashing the app.


🟢 Step 7: Real-time API with WebSockets (Example in NestJS)

Some apps need real-time updates, like a chat app or stock price tracker.

📌 7.1 NestJS WebSocket Example

import { WebSocketGateway, SubscribeMessage, WebSocketServer } from "@nestjs/websockets";
import { Server } from "socket.io";

@WebSocketGateway()
export class ChatGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage("message")
  handleMessage(client: any, payload: string): void {
    this.server.emit("message", payload); // Broadcast message to all clients
  }
}

✅ Now, any user can send a message, and all connected users receive it instantly.


🎯 Final Thoughts

By following these steps, you will master API integration:

✅ Understand API requests & responses

✅ Fetch data in the frontend (React, Next.js)

✅ Build an API in the backend (NestJS, Express)

✅ Handle authentication (API Keys, JWT)

✅ Test APIs using Postman

✅ Handle errors gracefully

✅ Work with real-time APIs using WebSockets