REST API Best Practices
Build better REST APIs. Learn HTTP methods and status codes.
REST API Best Practices
HTTP Methods
```javascript app.get('/api/products', async (req, res) => { const products = await Product.find(); res.json(products); });
app.get('/api/products/:id', async (req, res) => { const product = await Product.findById(req.params.id); if (!product) return res.status(404).json({ error: 'Not found' }); res.json(product); });
app.post('/api/products', async (req, res) => { const product = await Product.create(req.body); res.status(201).json(product); });
app.put('/api/products/:id', async (req, res) => { const product = await Product.findByIdAndUpdate( req.params.id, req.body, { new: true } ); res.json(product); });
app.delete('/api/products/:id', async (req, res) => { await Product.findByIdAndDelete(req.params.id); res.status(204).send(); }); ```
Status Codes
``` 200 OK → Successful GET, PUT, PATCH 201 Created → Successful POST 204 No Content → Successful DELETE 400 Bad Request → Invalid input 401 Unauthorized → Not authenticated 403 Forbidden → Not authorized 404 Not Found → Resource doesn't exist 500 Internal Error → Server error ```
Consistent Response Format
```javascript res.json({ success: true, data: products });
res.status(400).json({ success: false, error: { message: 'Invalid input', code: 'INVALID_INPUT' } }); ```
Filtering and Sorting
```javascript app.get('/api/products', async (req, res) => { const { category, minPrice, sortBy, order } = req.query; const query = {}; if (category) query.category = category; if (minPrice) query.price = { $gte: parseInt(minPrice) }; const sort = {}; if (sortBy) sort[sortBy] = order === 'desc' ? -1 : 1; const products = await Product.find(query).sort(sort); res.json({ success: true, data: products }); }); ```
Key Takeaway
Use proper HTTP methods and status codes. Consistent response format. Support filtering, sorting, pagination. Include helpful error messages.