DEV Community

Cover image for API Integration Mastery Roadmap (2025 Edition)
Taki (Kieu Dang)
Taki (Kieu Dang)

Posted on

4

API Integration Mastery Roadmap (2025 Edition)

πŸ“Œ 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));
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Expected API Response:

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

βœ… 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
}
Enter fullscreen mode Exit fullscreen mode

πŸ–₯️ 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));
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Expected API Response (confirmation of post creation):

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

βœ… 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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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
Enter fullscreen mode Exit fullscreen mode

πŸ–₯️ 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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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: "user@example.com",
    password: "password123"
  })
})
  .then(response => response.json())
  .then(data => {
    console.log("Login successful, JWT token:", data.token);
  })
  .catch(error => console.error("Error logging in:", error));
Enter fullscreen mode Exit fullscreen mode

βœ… The server responds with:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5..."
}
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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;
Enter fullscreen mode Exit fullscreen mode

βœ… 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: "john@example.com" },
      { id: 2, name: "Jane Doe", email: "jane@example.com" }
    ];
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή If you visit http://localhost:3000/users, the API will return:

[
  { "id": 1, "name": "John Doe", "email": "john@example.com" },
  { "id": 2, "name": "Jane Doe", "email": "jane@example.com" }
]
Enter fullscreen mode Exit fullscreen mode

βœ… 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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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
  }
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video πŸ“ΉοΈ

Top comments (1)

Collapse
 
ngtduc693 profile image
Duc Nguyen Thanh β€’

Good

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay