✅ Great — let’s break this down clearly so you actually *get it* once and for all:
---
1##1️⃣ **1 What is a REST API?**
**REST API** = **RE**presentational **S**tate **T**ransfer **A**pplication
**P**rogramming **I**nterface
That sounds scary — but the idea is super simple:
👉 It’s a **standard way** for different systems (like your frontend and backend) to
talk to each other over **HTTP** using **URLs**.
In practice:
- You expose **endpoints** like `/api/users` or `/api/products`.
- You use **HTTP methods**:
- `GET` — get data
- `POST` — create data
- `PUT` or `PATCH` — update data
- `DELETE` — delete data
- You send/receive **JSON** as the data format.
---
## 2️⃣
** Do APIs connect frontend and backend?**
✅ **YES!**
In a typical web app:
- The **frontend** (React, Next.js, plain HTML) makes **HTTP requests** (`fetch`,
`axios`) to the **backend REST API**.
- The **backend** (Express, Django, Rails, Laravel) handles the request, talks to
the **database**, and returns a JSON response.
💡 **API = the bridge** between your frontend and backend.
---
## 3️⃣
** Example: What does a REST API look like?**
| HTTP Method | URL | What it does |
|-------------|-----|---------------|
| GET | `/api/users` | Get all users |
| GET | `/api/users/123` | Get user with ID 123 |
| POST | `/api/users` | Create a new user |
| PUT | `/api/users/123` | Update user with ID 123 |
| DELETE | `/api/users/123` | Delete user with ID 123 |
---
## 4️⃣
** How do you create a REST API? (Express example)**
### ✅ Basic steps
**1) Install Express**
```bash
npm init -y
npm install express
```
**2) Create `server.js`**
```js
const express = require('express');
const app = express();
app.use(express.json()); // to parse JSON bodies
// Example in-memory "database"
let users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET one user
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id == 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 newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
// PUT update user
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id == req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
user.name = req.body.name;
res.json(user);
});
// DELETE user
app.delete('/api/users/:id', (req, res) => {
users = users.filter(u => u.id != req.params.id);
res.json({ message: 'User deleted' });
});
// Start server
app.listen(3000, () => {
console.log('API server running on http://localhost:3000');
});
```
✅ That’s it! You now have a working **REST API**.
---
## 🟢 **Direct Access vs API**
✅ Great — let’s make this **super clear**:
**What’s the difference between direct access to a database vs. using an API?**
**Direct DB Access:** Client connects directly to DB → risky, no validation,
security issues.
**API Access:** Frontend → API → DB. The API acts as a secure gatekeeper, using
prepared queries with variables.
---
## 🟢 **CRUD Queries with Variables**
You do write CRUD queries with variables.
Example:
```js
// SQL
const sql = 'SELECT * FROM users WHERE id = ?';
const [rows] = await db.query(sql, [userId]);
// Mongoose
const user = await User.findById(userId);
```
---
## 🟢 **Middlewares**
**Middleware**: functions that run in the middle of request-response cycle.
- Read/modify request/response.
- Call `next()` to pass to the next middleware.
Example:
```js
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
```
Used in GET, POST, etc.
**next()**: lets you chain multiple middlewares.
Example:
```js
app.post('/submit',
express.json(),
(req, res, next) => {
if (!req.body.name) return res.status(400).send('Name required');
next();
},
(req, res) => {
res.send(`Hello, ${req.body.name}!`);
}
);
```
**Key:** Use next() to pass control down the chain.