What We're Building
A simple API with products and users:
| Endpoint | Method | Description |
|---|---|---|
| /api/products | GET | Get all products |
| /api/products/:id | GET | Get one product |
| /api/products | POST | Create product |
| /api/products/:id | PUT | Update product |
| /api/products/:id | DELETE | Delete product |
Project Structure
📁 my-api/
├── 📄 index.js
├── 📄 package.json
└── 📁 models/
└── 📄 Product.js
Step 1: Setup
mkdir my-api
cd my-api
npm init -y
npm install express mongoose cors
Step 2: Product Model
// models/Product.js
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
category: { type: String, default: 'general' },
inStock: { type: Boolean, default: true }
}, { timestamps: true });
module.exports = mongoose.model('Product', productSchema);
Step 3: Main Server
// index.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const Product = require('./models/Product');
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Connect to MongoDB (using async/await with try/catch - better practice!)
async function connectDB() {
try {
await mongoose.connect('mongodb://localhost:27017/myapi');
console.log('✅ Connected to MongoDB');
} catch (error) {
console.error('❌ MongoDB connection error:', error.message);
process.exit(1); // Exit if database connection fails
}
}
connectDB(); // Call the function to connect
// GET all products
app.get('/api/products', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// GET one product
app.get('/api/products/:id', async (req, res) => {
try {
const product = await Product.findById(req.params.id);
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
res.json(product);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// POST create product
app.post('/api/products', async (req, res) => {
try {
const product = await Product.create(req.body);
res.status(201).json(product);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// PUT update product
app.put('/api/products/:id', async (req, res) => {
try {
const product = await Product.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
res.json(product);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// DELETE product
app.delete('/api/products/:id', async (req, res) => {
try {
const product = await Product.findByIdAndDelete(req.params.id);
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
res.json({ message: 'Product deleted' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Testing the API
Using PowerShell (Windows):
# Get all products
Invoke-RestMethod -Uri http://localhost:3000/api/products -Method Get
# Create product
$body = @{
name = "Laptop"
price = 999
} | ConvertTo-Json
Invoke-RestMethod -Uri http://localhost:3000/api/products -Method Post -Body $body -ContentType "application/json"
# Update product (replace ID_HERE with actual product ID)
$body = @{
price = 899
} | ConvertTo-Json
Invoke-RestMethod -Uri http://localhost:3000/api/products/ID_HERE -Method Put -Body $body -ContentType "application/json"
# Delete product (replace ID_HERE with actual product ID)
Invoke-RestMethod -Uri http://localhost:3000/api/products/ID_HERE -Method Delete
💡 PowerShell Tips:
Invoke-RestMethodis the PowerShell equivalent of curl-Methodspecifies GET, POST, PUT, DELETE-BodywithConvertTo-Jsonsends JSON data-ContentTypetells the server you're sending JSON- PowerShell automatically parses JSON responses for you
🎯 Key Takeaways:
- Use
cors()to allow React to connect - Use
express.json()to parse request body - Always use try/catch in async routes
- Return appropriate status codes (200, 201, 404, 500)