Understanding APIs: A Beginner's Story About How Apps Talk
API tutorial for beginners — understand what APIs are, how REST APIs work, HTTP methods, JSON, authentication, and how to call APIs in JavaScript with real examples.
Get more content like this on Telegram!
Daily AI tips, notes & resources — free
Understanding APIs: A Beginner's Story About How Apps Talk
When I started learning web development, I could build a page that looked great. But it was static — every time I refreshed, the same content appeared, hardcoded in my HTML.
I wanted to show real weather data. Real stock prices. Real photos. Real anything.
The answer was APIs — and once I understood them, my projects transformed from static mockups into real applications that connected to the world.
APIs power almost every app you use. When Instagram loads your feed, an API returns your posts. When you Google something, the Search API processes your query. When you pay for something online, a payments API handles the transaction. Understanding APIs is one of the most important skills a web developer can acquire.
What is an API?
API stands for Application Programming Interface. The "interface" part is key — it's a defined way two systems communicate.
The restaurant analogy is the clearest:
- You (the client app) look at a menu (API documentation)
- The waiter (the API) takes your order (request)
- The kitchen (the server/database) prepares your food
- The waiter brings it back (response)
You never go into the kitchen. You don't know (or care) how the food is prepared. You just know what you can order and what format it arrives in.
Real-world example: When your weather app shows tomorrow's forecast, it doesn't have meteorological data — it asks a weather API. The API queries weather databases, processes the data, and returns structured JSON that your app displays. The app never accesses the weather databases directly.
HTTP Methods: The Verbs of REST APIs
REST APIs use HTTP methods to indicate what operation you want to perform:
| Method | Operation | Example |
|---|---|---|
| GET | Read / retrieve | GET /users/5 — get user #5 |
| POST | Create | POST /posts — create a new post |
| PUT | Update (full) | PUT /posts/3 — replace post #3 |
| PATCH | Update (partial) | PATCH /posts/3 — update part of post #3 |
| DELETE | Delete | DELETE /posts/3 — delete post #3 |
RESTful URL Design
REST APIs use URLs to represent resources (nouns), not actions (verbs):
# Good — resources and methods
GET /api/users → list all users
GET /api/users/42 → get user #42
POST /api/users → create a user
PUT /api/users/42 → update user #42
DELETE /api/users/42 → delete user #42
# Bad — verbs in URLs
GET /api/getUsers
POST /api/createUser
GET /api/deleteUser?id=42
JSON: The Language of APIs
Most APIs communicate using JSON (JavaScript Object Notation):
{
"id": 42,
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "developer",
"skills": ["JavaScript", "React", "Node.js"],
"address": {
"city": "London",
"country": "UK"
},
"active": true
}
JSON supports:
- Strings:
"text" - Numbers:
42,3.14 - Booleans:
true,false - Arrays:
["item1", "item2"] - Objects:
{"key": "value"} - Null:
null
Making API Calls in JavaScript
The Fetch API
// GET request — fetch data
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const user = await response.json();
console.log(user.name);
return user;
}
// POST request — send data
async function createPost(postData) {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiToken}`,
},
body: JSON.stringify(postData),
});
const newPost = await response.json();
return newPost;
}
For a deep dive into async/await and Promises, see our JavaScript fundamentals guide. The JavaScript async/await guide covers everything you need to understand these patterns.
A Real Example: OpenWeather API
const API_KEY = 'your_api_key_here';
const city = 'London';
async function getWeather(city) {
try {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Weather API error: ${response.status}`);
}
const data = await response.json();
return {
city: data.name,
temp: data.main.temp,
description: data.weather[0].description,
humidity: data.main.humidity,
};
} catch (error) {
console.error('Failed to fetch weather:', error);
return null;
}
}
// Usage
getWeather('London').then(weather => {
if (weather) {
document.getElementById('temp').textContent = `${weather.temp}°C`;
document.getElementById('desc').textContent = weather.description;
}
});
HTTP Status Codes
Every API response includes a status code that tells you what happened:
200 OK — Success. Response body contains the data.
201 Created — Resource was created (response to POST).
204 No Content — Success, but no body (common for DELETE).
400 Bad Request — Your request has invalid data.
401 Unauthorized — Authentication required or invalid.
403 Forbidden — Authenticated but not allowed to do this.
404 Not Found — Resource doesn't exist.
422 Unprocessable — Valid format but invalid data (validation errors).
429 Too Many Requests— Rate limit exceeded. Slow down.
500 Internal Error — Server error. Not your fault.
503 Unavailable — Server is down or overloaded.
Always check response.ok (true for 200–299) before parsing the body.
API Authentication
Most real APIs require authentication to identify who is making requests.
API Keys (Simplest)
// Query parameter
fetch(`https://api.example.com/data?api_key=YOUR_KEY`)
// Header (more secure — key not in URL/logs)
fetch('https://api.example.com/data', {
headers: { 'X-API-Key': 'YOUR_KEY' }
})
Bearer Tokens (JWT)
fetch('https://api.example.com/profile', {
headers: {
'Authorization': `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`
}
})
Never Expose API Keys in Frontend Code
API keys in frontend JavaScript are visible to anyone who views source. Use environment variables:
// .env file (never commit to git)
VITE_WEATHER_API_KEY=abc123
// In your code
const apiKey = import.meta.env.VITE_WEATHER_API_KEY;
For APIs that must be kept secret (payment keys, admin tokens), use a server-side proxy — your frontend calls your own server, your server calls the third-party API with the secret key.
Reading API Documentation
Every API has documentation describing its endpoints. Here's how to read it:
Base URL: https://api.example.com/v2
Authentication: Bearer token in Authorization header
Rate limit: 100 requests per minute
Endpoint:
GET /users/{id}
Parameters:
id (path) — User ID, required
Headers:
Authorization: Bearer {token}
Response 200:
{
"id": integer,
"name": string,
"email": string
}
The {id} in the path is a path parameter — replace it with the actual value. Always check the rate limits — exceeding them returns a 429 error and may temporarily block your app.
For understanding the underlying protocol that powers all API communication, our how the internet works guide covers HTTP in detail.
Frequently Asked Questions
What is an API?
A defined interface for two software systems to communicate. One app requests data or actions, another provides them, without either exposing internal code.
What is a REST API?
An API that uses HTTP methods (GET/POST/PUT/DELETE) and URLs to represent operations on resources.
What is JSON?
A human-readable text format for structured data. The standard format for API responses.
What is an API key?
A secret string that identifies who's making requests. Never expose in frontend code — use environment variables.
GET vs POST?
GET reads data (safe to repeat). POST creates or triggers something (calling twice = two things created).
Frequently Asked Questions
AiTechWorlds Team
✓ Verified WriterThe AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.
Related Articles
The Web Developer's Guide to Chrome DevTools (Hidden Features)
Chrome DevTools guide for web developers — master the Elements panel, Network tab, Console, Performance profiler, and hidden features most developers never use.
CSS Grid vs Flexbox: When to Use Which Layout Method
CSS Grid vs Flexbox explained clearly — understand the difference, when each layout method excels, and how to choose the right one for every UI pattern.
Docker for Beginners: Containers Explained Without the Jargon
Docker tutorial for beginners — learn containers vs VMs, Docker images, Dockerfiles, docker-compose, and how to containerize a real web application step by step.
Git for Beginners: Stop Fearing Version Control, Start Loving It
Git tutorial for beginners — learn the essential git commands, branching, merging, and GitHub workflow with real examples that make version control click.