API
Introduction to APIs
An API (Application Programming Interface) is a contract that lets two pieces of software talk to each other. A web API lets a client (browser, mobile app) request data and actions from a server over HTTP.
How a web request works
Client Server
│ ── HTTP Request ──────────▶ │
│ GET /api/users/42 │
│ │ (looks up user)
│ ◀────── HTTP Response ────── │
│ 200 OK { "name": "Priya" } │
The client sends a request (method + URL + optional headers/body); the server returns a response (status code + headers + body, usually JSON).
JSON — the data format of the web
Most APIs exchange JSON (JavaScript Object Notation): lightweight, human-readable, and natively parsed by JavaScript.
{
"id": 42,
"name": "Priya Sharma",
"skills": ["JavaScript", "React"],
"active": true
}
Making a request in JavaScript
The browser's fetch API is the standard way to call an API:
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
return user;
}
getUser(42).then((user) => console.log(user.name));
💡
fetch returns a Response object — you must call .json() (which is itself async) to read the parsed body. Always check response.ok to handle errors.
Watch & Learn
A recommended video to watch alongside this chapter.
More “Introduction to APIs” videos on YouTube