API Calls — Getting Data For You
EXAMPLE: Calling the OpenWeather API to get current weather, or calling Stripe's API to process a payment.
You're interacting with someone else's system through a defined interface.
API calls are requests to an external service over a network — this is where HTTP and HTTPS comes into play! You interact with this more than you think!
API calls are basically you asking another system to give you data or perform an action on your behalf (POST, GET, etc.)
Analogy: Think of an API as a waiter at a restaurant. You (the client) don't go into the kitchen and cook your own food. Instead, you tell the waiter what you want, they take your request to the kitchen, and bring back your meal. APIs work the same way — they're intermediaries that let different software systems talk to each other.
ⓘ Don't forget: You can call an API on your own database too!
▲ PROS
- You don't have to build or maintain the underlying service yourself
- The provider handles scalability, updates, and infrastructure
- Access to specialized functionality you couldn't easily replicate
- You only pay for what you use (ideally...)
|
▼ CONS
- Slower — network latency adds significant overhead 50-500ms+
- Dependent on another service's uptime and reliability
- Costs can add up with high usage
- Rate limits may constrain your application
- Less control over data format and availability
|
Database Queries — Your Own Data
EXAMPLE: SELECT * FROM users WHERE id = 5 to fetch a user from your PostgreSQL database.
Database queries are direct requests to your own database to read or write data. You're using SQL (or another query language) to interact with data you control and store.
A database query is a direct request to a database to read, write, update, or delete data. You're not going over HTTP or the internet — you're directly communicating with a database server using a database protocol, not HTTP.
▲ PROS
- Much faster — typically 1-50ms since it's local
- Complete control over your data
- No external dependencies or rate limits
- Predictable costs
- Works offline or in isolated environments
|
▼ CONS
- You have to build, maintain, and scale the database yourself
- Limited to data you've collected and stored
- Infrastructure costs are on you
- You need to handle backups, security, and maintenance
|
Key Differences at a Glance
DB Database Query
- Direct connection to database
- Uses SQL or other query language
- Server-side only (browsers can't directly query DBs)
- FAST 1-50ms typically
- Returns raw data from tables
|
API API Call
- HTTP request over network
- Uses REST, GraphQL, etc.
- Can happen from anywhere (frontend, backend, mobile)
- SLOWER 50-500ms+ due to network
- Returns formatted response (usually JSON)
|
Side by Side: Get a User by ID
Option 1: Direct Database Query server-side only
// This runs on your server
const [rows] = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
const user = rows[0];
// Fast: ~5-20ms
Option 2: API Call can run anywhere
// This can run anywhere (frontend, mobile app, etc.)
const response = await fetch(`/api/users/${userId}`);
const user = await response.json();
// Slower: ~100-300ms (includes network time + processing)
Why Not Always Use Direct DB Queries?
The answer: Security and separation of concerns.
BAD — Never do this on the frontend:
// Frontend code - BAD!
const db = connectToDatabase({
host: 'mydb.com',
username: 'admin',
password: 'secret123' // EXPOSED TO BROWSER!
});
const users = await db.query('SELECT * FROM users');
Problems with the above:
- Your database credentials are exposed in the browser
- Anyone can modify the query and steal/delete data
- No validation or business logic
- No rate limiting
Do this instead:
// Frontend calls your API
const response = await fetch('/api/users');
const users = await response.json();
// app/api/users/route.js - Backend (safe)
export async function GET() {
// Database credentials stay on server
const [rows] = await db.query('SELECT id, name, email FROM users');
// You control what data is returned
// You can add authentication checks
// You can validate requests
// You can add rate limiting
return Response.json({ users: rows });
}
The Complete Picture
Browser / Frontend
|
| HTTP Request (fetch)
v
Your Next.js API Route (/app/api/...)
|
| SQL Query (db.query)
v
Your Database (PostgreSQL, MySQL, etc.)
|
| Returns raw data
v
Your API Route (processes, formats)
|
| HTTP Response (JSON)
v
Browser / Frontend (displays data)
Your Next.js API Route can ALSO call external APIs:
|
|--- Your Database (SQL query)
|
+--- External API (Stripe, OpenAI, etc.)
Summary Comparison Table
| Aspect |
Database Query |
API Call |
| Speed |
FAST 1–50ms |
SLOWER 50–500ms+ |
| Where it runs |
Server-side only |
Anywhere (browser, mobile, etc.) |
| Protocol |
Database protocol (MySQL, PostgreSQL) |
HTTP / HTTPS |
| Language |
SQL or ORM methods |
REST, GraphQL, etc. |
| Security |
Must keep credentials secret |
Can be called publicly (with auth) |
| Use case |
Direct data access on server |
Communication between systems |
When to Use What
Use Direct Database Queries when:
- You're writing server-side code (API routes, server components)
- You need maximum performance
- You're doing complex data operations
|
Use API Calls when:
- You're in the browser / frontend
- You're calling external services
- You need to abstract business logic
- You want to reuse endpoints across multiple clients (web, mobile, etc.)
|
For API practice || PokeAPI
These Notes Were Last updated: 11-03-2026