π 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: "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));
β
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: "john@example.com" },
{ id: 2, name: "Jane Doe", email: "jane@example.com" }
];
}
}
πΉ 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" }
]
β 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
Top comments (1)
Good