Q1. What are the steps to build a RESTful API with Express?
Setup: install Express, database (e.g., MongoDB with Mongoose). Define models, create routes (GET, POST, PUT, DELETE), implement controllers with CRUD logic, add authentication (JWT), validation, error handling, and test with Postman.
Q2. How do you structure routes for a RESTful API?
Use Express.Router(). Group by resource: usersRouter, productsRouter. Follow REST conventions: GET /users, POST /users, GET /users/:id, PUT /users/:id, DELETE /users/:id. Keep route handlers thin - delegate to controller functions.
Q3. How do you add authentication to your API?
Implement JWT authentication. Create register/login endpoints that return tokens. Create auth middleware to verify tokens. Protect routes by adding the middleware. Optionally implement role-based authorization for different permissions.
Q4. How do you handle validation for API requests?
Use express-validator or Joi. Validate request body, params, and query. Check required fields, data types, formats. Return meaningful error messages with 400 status. Example: body('email').isEmail().withMessage('Invalid email').
Q5. What response formats should your API return?
Use JSON consistently. Include appropriate status codes: 200 for success, 201 for created, 400 for bad request, 401 unauthorized, 404 not found, 500 server error. Structure responses consistently, e.g., { success: true, data: ... } or { error: message }.
