Lesson 4.1: What is an API
Duration: 45 minutes
Learning Objectives
By the end of this lesson, you will be able to:
- Explain what an API is in simple terms
- Understand why APIs are essential for modern applications
- Distinguish between different types of APIs
- Describe how web APIs work at a high level
- Identify common real-world API use cases
Introduction
Every time you check the weather on your phone, scroll through social media, or pay for something online, you are using APIs. But what exactly is an API?
Think of an API like a waiter at a restaurant. You (the customer) want food from the kitchen (the server/database), but you cannot just walk into the kitchen yourself. The waiter takes your order, communicates it to the kitchen in a way they understand, and brings back your food. The waiter is the API - the middleman that allows two systems to communicate.
What is an API?
API stands for Application Programming Interface. Let us break that down:
- Application: A piece of software
- Programming: Code that makes things work
- Interface: A point where two systems meet and interact
An API is a contract that defines how two pieces of software can talk to each other. It specifies:
- What requests you can make
- How to make those requests
- What responses you will get back
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ │ │ │ │ │
│ Your App │───────>│ API │───────>│ Server / │
│ (Client) │ │ (Interface) │ │ Database │
│ │<───────│ │<───────│ │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Request Data
Response
Why Do APIs Exist?
1. Security and Control
APIs act as gatekeepers. Instead of giving everyone direct access to a database (dangerous!), APIs expose only specific operations.
// Without API: Direct database access (BAD!)
// Anyone could delete all your users
// With API: Controlled access (GOOD!)
// The API decides what operations are allowed
// GET /users - allowed
// DELETE /database - not exposed, protected
2. Abstraction
APIs hide complexity. You do not need to know how Twitter stores tweets or how Stripe processes payments. You just use their API.
// You don't need to know HOW this works internally
const weather = await fetch('https://api.weather.com/current?city=London');
// The API handles:
// - Database queries
// - Data formatting
// - Caching
// - Authentication
// - Rate limiting
3. Reusability
One API can serve multiple clients: web apps, mobile apps, desktop apps, other services.
┌──────────────┐
│ Web App │
└──────┬───────┘
│
┌──────────────┐ ┌──────▼───────┐ ┌──────────────┐
│ Mobile App │───>│ API │<───│ Desktop App │
└──────────────┘ └──────┬───────┘ └──────────────┘
│
┌──────▼───────┐
│ Database │
└──────────────┘
4. Integration
APIs allow different services to work together. Your app can use Google Maps for directions, Stripe for payments, and Twilio for SMS - all through their APIs.
Types of APIs
Web APIs (HTTP APIs)
The most common type. They use HTTP protocol over the internet.
// Web API request
const response = await fetch('https://api.example.com/users');
const users = await response.json();
REST APIs
A style of web API following specific conventions. We will focus on these.
// RESTful endpoints follow patterns
GET / users; // Get all users
GET / users / 1; // Get user with id 1
POST / users; // Create new user
PUT / users / 1; // Update user 1
DELETE / users / 1; // Delete user 1
GraphQL APIs
A query language for APIs. You request exactly the data you need.
# GraphQL query
query {
user(id: 1) {
name
email
posts {
title
}
}
}
WebSocket APIs
For real-time, bidirectional communication (chat apps, live updates).
Library/Framework APIs
APIs within code libraries. When you use Array.map() in JavaScript, you are using an API.
// JavaScript Array API
const numbers = [1, 2, 3];
const doubled = numbers.map((n) => n * 2); // Using the Array.map API
Anatomy of a Web API Request
When you make a request to a web API, you need several things:
1. Endpoint (URL)
The address where the API lives.
https://api.example.com/v1/users
└─────────┬─────────┘ └┬┘ └──┬──┘
Base URL Version Resource
2. HTTP Method
What action you want to perform (GET, POST, PUT, DELETE).
3. Headers
Metadata about the request (authentication, content type).
const headers = {
Authorization: 'Bearer your-token',
'Content-Type': 'application/json',
};
4. Body (for POST/PUT)
The data you are sending.
const body = JSON.stringify({
name: 'John',
email: 'john@example.com',
});
5. Query Parameters (optional)
Filters or options appended to the URL.
https://api.example.com/users?role=admin&limit=10
└────────┬────────┘
Query Parameters
API Response
When an API responds, you get:
1. Status Code
A number indicating success or failure.
| Code | Meaning |
|---|---|
| 200 | OK - Success |
| 201 | Created - Resource created |
| 400 | Bad Request - Your fault |
| 401 | Unauthorized - Need to log in |
| 404 | Not Found - Resource does not exist |
| 500 | Server Error - Their fault |
2. Response Headers
Metadata about the response.
3. Response Body
The actual data, usually in JSON format.
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
Real-World API Examples
Weather Data
// OpenWeatherMap API
const response = await fetch(
'https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY'
);
const weather = await response.json();
console.log(weather.main.temp); // Temperature in Kelvin
GitHub Users
// GitHub API (no auth needed for public data)
const response = await fetch('https://api.github.com/users/octocat');
const user = await response.json();
console.log(user.name); // "The Octocat"
Placeholder Data for Testing
// JSONPlaceholder - free fake API
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await response.json();
console.log(post.title);
API Documentation
Every good API has documentation that tells you:
- Available endpoints: What URLs you can call
- Methods: What HTTP methods each endpoint accepts
- Parameters: What data you need to send
- Response format: What data you will get back
- Authentication: How to prove you are allowed to use the API
- Rate limits: How many requests you can make
Example documentation entry:
GET /users/{id}
Description: Get a user by ID
Parameters:
- id (path, required): The user's ID
Response:
{
"id": number,
"name": string,
"email": string
}
Example:
GET /users/1
Response:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
Common API Authentication Methods
Most APIs require authentication to identify who is making requests.
1. API Keys
A simple string you include in requests.
// API key in query parameter
fetch('https://api.example.com/data?api_key=abc123');
// API key in header
fetch('https://api.example.com/data', {
headers: {
'X-API-Key': 'abc123',
},
});
2. Bearer Tokens
Tokens (often JWTs) sent in the Authorization header.
fetch('https://api.example.com/data', {
headers: {
Authorization: 'Bearer eyJhbGciOiJIUzI1NiIs...',
},
});
3. OAuth
A protocol for authorization, often used for "Login with Google/GitHub".
Practical Example: Your First API Call
Let us make a real API call to JSONPlaceholder, a free fake API for testing.
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
async function getPost(postId: number): Promise<Post> {
const url = `https://jsonplaceholder.typicode.com/posts/${postId}`;
console.log(`Fetching: ${url}`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const post: Post = await response.json();
return post;
}
// Usage
async function main() {
try {
const post = await getPost(1);
console.log('Title:', post.title);
console.log('Body:', post.body);
} catch (error) {
console.error('Failed to fetch post:', error);
}
}
main();
Output:
Fetching: https://jsonplaceholder.typicode.com/posts/1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body: quia et suscipit...
Exercise
Exercise 1: Identify API Components
Look at this API call and identify all the components:
const response = await fetch(
'https://api.github.com/repos/microsoft/TypeScript/issues?state=open&per_page=5',
{
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: 'Bearer ghp_xxxx',
},
}
);
Solution
- Base URL:
https://api.github.com - Endpoint/Resource:
/repos/microsoft/TypeScript/issues - Query Parameters:
state=openper_page=5
- HTTP Method: GET (default for fetch)
- Headers:
Accept: Specifies response formatAuthorization: Bearer token for authentication
Exercise 2: Match Status Codes
Match each scenario with the appropriate HTTP status code:
- User tries to access a page that does not exist
- Request was successful
- User forgot to include required API key
- Server crashed while processing request
- New user account was created successfully
Status codes: 200, 201, 401, 404, 500
Solution
- 404 - Not Found
- 200 - OK
- 401 - Unauthorized
- 500 - Internal Server Error
- 201 - Created
Exercise 3: Read API Documentation
Visit JSONPlaceholder and answer:
- What resources are available?
- How would you get all comments for post #1?
- What fields does a User resource have?
Solution
- Resources: posts, comments, albums, photos, todos, users
GET /posts/1/commentsorGET /comments?postId=1- User fields: id, name, username, email, address, phone, website, company
Key Takeaways
- An API is a contract that defines how two software systems communicate
- Web APIs use HTTP to send requests and receive responses over the internet
- Every API request has: endpoint, method, optional headers and body
- Every API response has: status code, headers, and body
- REST is an architectural style that uses HTTP methods for CRUD operations
- API documentation is essential - always read it before using an API
- Most APIs require authentication (API keys, tokens, OAuth)
- Status codes tell you if the request succeeded or why it failed
Resources
| Resource | Type | Level |
|---|---|---|
| MDN: HTTP Overview | Documentation | Beginner |
| What is an API? (RedHat) | Article | Beginner |
| JSONPlaceholder | API | Beginner |
| HTTP Status Codes | Documentation | Beginner |
Next Lesson
Now that you understand what APIs are, let us dive deeper into HTTP methods and learn when to use GET, POST, PUT, and DELETE.