Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views4 pages

API Rest Crud Middleware Full

This document provides a comprehensive overview of REST APIs, explaining their purpose as a standard method for frontend and backend systems to communicate over HTTP using JSON. It details the basic HTTP methods used in REST APIs, how to create a simple REST API using Express, and the differences between direct database access and API access. Additionally, it covers the concept of middleware in the request-response cycle, illustrating its use with examples.

Uploaded by

mhrb54824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views4 pages

API Rest Crud Middleware Full

This document provides a comprehensive overview of REST APIs, explaining their purpose as a standard method for frontend and backend systems to communicate over HTTP using JSON. It details the basic HTTP methods used in REST APIs, how to create a simple REST API using Express, and the differences between direct database access and API access. Additionally, it covers the concept of middleware in the request-response cycle, illustrating its use with examples.

Uploaded by

mhrb54824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

✅ 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.

You might also like