Day 75 REST API with Express
Professional REST API banane ke liye proper structure, input validation, meaningful error messages, aur correct HTTP status codes zaroori hain. Yeh sab milke production-ready API banti hai.
Proper REST API Structure
Well-organized Express API.
// Helper functions
const successResponse = (res, data, statusCode = 200) => {
res.status(statusCode).json({ success: true, data });
};
const errorResponse = (res, message, statusCode = 400) => {
res.status(statusCode).json({ success: false, error: message });
};
// Validation middleware
function validateUser(req, res, next) {
const { name, email } = req.body;
const errors = [];
if (!name || name.trim().length < 2) {
errors.push("Name must be at least 2 characters");
}
if (!email || !/^[^s@]+@[^s@]+.[^s@]+$/.test(email)) {
errors.push("Valid email required");
}
if (errors.length > 0) {
return res.status(422).json({
success: false,
errors,
message: "Validation failed"
});
}
next(); // validation passed
}
// Routes with validation
app.post("/api/users", validateUser, (req, res) => {
const user = createUser(req.body);
successResponse(res, user, 201);
});
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
error: "Internal Server Error"
});
});
// 404 handler
app.use((req, res) => {
errorResponse(res, `Route ${req.method} ${req.path} not found`, 404);
});
🎯 Practice Challenge
Todo REST API banao with proper validation, error handling, filtering (completed/pending), aur pagination. Postman se test karo.