What is a REST API?
An API (Application Programming Interface) lets programs talk to each other. REST is a style of building APIs that uses standard web protocols.
The Restaurant Analogy
Think of a REST API like a restaurant:
- You (the client) want food
- The menu shows what's available (API documentation)
- The waiter takes your order (the API)
- The kitchen prepares it (the server)
- The response is your food (JSON data)
You don't need to know how the kitchen works. You just follow the menu.
HTTP Methods (CRUD Operations)
REST uses HTTP methods to describe actions:
| Method | Purpose | Example |
|--------|---------|---------|
| GET | Read data | Get user profile |
| POST | Create new | Create new user |
| PUT | Update (replace) | Update entire profile |
| PATCH | Update (partial) | Change just the email |
| DELETE | Remove | Delete user |
Endpoints
Endpoints are URLs that represent resources:
GET /users → List all users
GET /users/123 → Get user 123
POST /users → Create a user
PUT /users/123 → Replace user 123
DELETE /users/123 → Delete user 123
The URL is a noun (what), the method is a verb (action).
Status Codes
Servers respond with status codes:
| Code | Meaning |
|------|---------|
| 200 | OK - Success |
| 201 | Created - New resource made |
| 400 | Bad Request - You sent invalid data |
| 401 | Unauthorized - Login required |
| 403 | Forbidden - You can't access this |
| 404 | Not Found - Resource doesn't exist |
| 500 | Server Error - Something broke |
A Real Example
Request:
GET /api/users/123
Authorization: Bearer abc123
Response:
{
"id": 123,
"name": "Alice",
"email": "alice@example.com",
"created_at": "2024-01-15T10:30:00Z"
}
JSON: The Language of APIs
Most REST APIs use JSON (JavaScript Object Notation):
{
"string": "text value",
"number": 42,
"boolean": true,
"array": [1, 2, 3],
"object": { "nested": "value" }
}
It's human-readable and every language can parse it.
Key Principles of REST
1. Stateless: Each request contains all needed info
2. Resource-based: URLs represent things, not actions
3. Standard methods: Use HTTP verbs consistently
4. JSON responses: Structured, predictable data
Making API Requests
In JavaScript:
// GET request
const response = await fetch('/api/users/123');
const user = await response.json();
// POST request
const newUser = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Bob', email: 'bob@example.com' })
});
Summary
REST APIs are just a standardized way for programs to communicate over HTTP. Learn the patterns once, use them everywhere.