Every modern app — from weather widgets to social media feeds — runs on APIs (Application Programming Interfaces). Understanding APIs is one of the most important skills for any developer. This guide explains REST and GraphQL from scratch, with real code you can run today.
🔌 What is an API?
An API is a set of rules that lets different software applications communicate. When you check the weather on your phone, the app sends a request to a weather API, which sends back a response with the data.
🌐 REST API — The Standard
REST (Representational State Transfer) uses standard HTTP methods to perform operations on resources:
| HTTP Method | Action | Example |
|---|---|---|
GET | Read data | GET /api/users |
POST | Create new data | POST /api/users |
PUT | Update existing data | PUT /api/users/1 |
DELETE | Remove data | DELETE /api/users/1 |
Building a REST API with Node.js & Express
import express from 'express';
const app = express();
app.use(express.json());
// In-memory database
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' }
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET single user
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// POST create user
app.post('/api/users', (req, res) => {
const user = {
id: users.length + 1,
name: req.body.name,
email: req.body.email
};
users.push(user);
res.status(201).json(user);
});
// DELETE user
app.delete('/api/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.status(204).send();
});
app.listen(3000, () => console.log('API running on port 3000'));
Consuming a REST API (Frontend)
// Fetch all users
const response = await fetch('https://api.example.com/users');
const users = await response.json();
// Create a new user
const newUser = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Charlie',
email: 'charlie@example.com'
})
});
// Error handling pattern
async function apiCall(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error('API Error:', err.message);
return null;
}
}
🔮 GraphQL — Ask for Exactly What You Need
GraphQL is a query language for APIs. Instead of multiple REST endpoints, you have one endpoint and specify exactly what data you want.
# GraphQL Query — Get only what you need
query {
user(id: 1) {
name
email
posts {
title
createdAt
}
}
}
# Response — No over-fetching!
{
"data": {
"user": {
"name": "Alice",
"email": "alice@example.com",
"posts": [
{ "title": "My First Post", "createdAt": "2026-01-15" }
]
}
}
}
⚖️ REST vs GraphQL — When to Use Each
| Criteria | REST | GraphQL |
|---|---|---|
| Learning Curve | Easy ✅ | Moderate |
| Data Fetching | Fixed structure | Flexible queries ✅ |
| Over-fetching | Common issue | Solved ✅ |
| Caching | Built-in HTTP caching ✅ | Needs custom setup |
| Best For | Simple CRUD, public APIs | Complex data, dashboards |
🎯 Beginner Advice: Start with REST — it's simpler, widely used, and most job listings require it. Learn GraphQL once you're comfortable with REST and encounter scenarios where you need more flexible data fetching (like building dashboards or mobile apps with varied screen sizes).