Episode 3 — NodeJS MongoDB Backend Architecture / 3.9 — REST API Development

3.9 — Exercise Questions: REST API Development

Practice questions for all six subtopics in Section 3.9. Mix of conceptual, coding, and hands-on exercises. Try each without reopening the lesson files first.

How to use this material (instructions)

  1. Read lessons in order -- README.md, then 3.9.a through 3.9.f.
  2. Answer closed-book first -- write an answer, then compare to the lesson.
  3. Code exercises -- build working Express snippets for every coding question.
  4. Redo misses -- retry wrong questions after sleep (spaced repetition).
  5. Interview prep -- pair with 3.9-Interview-Questions.md.

3.9.a -- What is a REST API (Q1-Q10)

Q1. What does REST stand for, and who coined the term?

Q2. REST is often called a "protocol." Why is that incorrect? What is it instead?

Q3. List the 6 REST constraints. Which one is optional?

Q4. Explain the difference between stateless and stateful communication. Give an example of how JWTs enable statelessness.

Q5. What is the Uniform Interface constraint? Name its 4 sub-constraints.

Q6. Convert these RPC-style endpoints to proper REST:

POST /api/getUsers
POST /api/deleteUser?id=42
POST /api/updateUserName
POST /api/createUser

Q7. What is the Richardson Maturity Model? Describe each level (0-3) in one sentence.

Q8. What is HATEOAS? Write a sample JSON response for GET /api/users/42 that includes HATEOAS links.

Q9. Compare REST, SOAP, and GraphQL in a table with at least 5 criteria.

Q10. Coding exercise: Build a complete CRUD REST API for a Book resource (title, author, isbn, year) using Express with an in-memory array. Include proper status codes (200, 201, 204, 404).


3.9.b -- API Versioning (Q11-Q18)

Q11. Why is API versioning necessary? Give 3 scenarios where you MUST create a new version.

Q12. Give 3 scenarios where you do NOT need a new version.

Q13. Write the URL, header, and query parameter versions of accessing "version 2 of the users endpoint."

Q14. Which versioning strategy do most public APIs use? Name 3 real companies that use it.

Q15. Coding exercise: Create an Express app with two versioned routers:

  • /api/v1/products returns [{ id, name, price }]
  • /api/v2/products returns [{ id, name, price, currency, discount }] with pagination

Q16. What is the Sunset header (RFC 8594)? Write Express middleware that adds it to deprecated routes.

Q17. Explain a strategy for sharing business logic between v1 and v2 routes without code duplication.

Q18. Design a deprecation timeline for shutting down API v1. Include at least 4 phases with actions for each.


3.9.c -- Postman for API Testing (Q19-Q28)

Q19. What are the 5 body types available in Postman? When would you use each?

Q20. Explain the difference between path parameters (:id) and query parameters (?page=2) in Postman.

Q21. What are Postman environment variables? Give 3 examples of variables you would create for local vs production environments.

Q22. Write a Postman test script that verifies:

  • Status code is 200
  • Response time is under 500ms
  • Response body has a data array with at least 1 item
  • Each item has id, name, and email properties

Q23. Write a Postman pre-request script that generates a random email and sets it as an environment variable.

Q24. Explain how to set up a login flow in Postman where the token from login is automatically used in all subsequent requests.

Q25. What is the Postman Collection Runner? Describe a 5-step CRUD test workflow you would run with it.

Q26. How do you export a Postman collection and share it with your team via Git?

Q27. What is Thunder Client and when might you prefer it over Postman?

Q28. Hands-on exercise: Using Postman (or Thunder Client), test all 5 CRUD operations against a REST API you have built. Take screenshots of each request/response.


3.9.d -- Status Codes in Practice (Q29-Q38)

Q29. For each status code, give a one-line description and an Express use case: 200, 201, 204, 400, 401, 403, 404, 409, 422, 429, 500, 502, 503.

Q30. What is the difference between 401 and 403? Give a real scenario for each.

Q31. When should you return 422 instead of 400?

Q32. What HTTP header should accompany a 201 Created response? Write the Express code.

Q33. Why should you use res.status(204).send() instead of res.status(204).json({}) for deletes?

Q34. Coding exercise: Create an ApiError class with static factory methods for: badRequest(), unauthorized(), forbidden(), notFound(), conflict(), tooMany(), internal().

Q35. Write a global Express error handler that:

  • Handles ApiError instances
  • Handles Mongoose ValidationError
  • Handles Mongoose duplicate key error (code 11000)
  • Returns a generic message in production, detailed message in development

Q36. Draw the status code decision flowchart from memory. What order should you check: auth, validation, existence, rate limit?

Q37. Design a consistent error response format for your API. What fields should every error response include?

Q38. Coding exercise: Build a middleware that automatically catches Mongoose CastError (invalid ObjectId) and returns a clean 400 response instead of a 500.


3.9.e -- Input Validation and Sanitization (Q39-Q48)

Q39. Why is server-side validation mandatory even when you have client-side validation?

Q40. What is the difference between validation and sanitization? Give 3 examples of each.

Q41. Using express-validator, write validators for a user registration form with:

  • name (required, 2-50 chars, trimmed)
  • email (required, valid email, normalized, unique check)
  • password (min 8 chars, 1 uppercase, 1 number, 1 special char)
  • confirmPassword (must match password)
  • age (optional, integer, 13-120)

Q42. Write a reusable validate() middleware function that runs an array of express-validator checks and returns a consistent 400 error response.

Q43. Using Zod, write a schema for the same user registration form from Q41.

Q44. Explain .parse() vs .safeParse() in Zod. When would you use each?

Q45. Write a custom validator in express-validator that checks if an event date is in the future.

Q46. Coding exercise: Build a GET /api/products search endpoint with validated query params:

  • q (optional, 1-100 chars, trimmed, escaped)
  • category (optional, must be one of 5 predefined values)
  • minPrice / maxPrice (optional, float >= 0, max must be >= min)
  • page / limit (optional, positive integers, limit max 100)

Q47. Compare express-validator and Zod in a table with at least 6 criteria.

Q48. What does normalizeEmail() do? What does escape() do? Why are both important?


3.9.f -- API Security (Q49-Q60)

Q49. List 7 security layers you should apply to an Express API and what each protects against.

Q50. Write express-rate-limit configurations for:

  • General API: 100 req/15 min
  • Login endpoint: 10 req/15 min (skip successful)
  • Account creation: 5 req/hour

Q51. What does helmet() do? List 5 HTTP headers it sets and what each prevents.

Q52. Why is app.use(cors()) with no options dangerous? Write a secure CORS configuration.

Q53. Explain the 3 types of XSS attacks (stored, reflected, DOM-based). For each, give one prevention strategy.

Q54. How does CSRF work against cookie-based authentication? Why are JWT APIs (using Authorization headers) naturally immune?

Q55. Demonstrate a NoSQL injection attack against a MongoDB login query. Then show 3 ways to prevent it.

Q56. Why should you use express.json({ limit: '10kb' }) instead of express.json()?

Q57. From the OWASP API Security Top 10, explain any 5 risks and their Express mitigations.

Q58. Coding exercise: Build a complete Express security setup with: helmet, CORS (strict), rate limiting (different for auth vs general), body size limits, mongo-sanitize, and a production-safe error handler.

Q59. Write test cases (using your preferred test framework) that verify:

  • Security headers are set correctly
  • Oversized payloads return 413
  • Rate limiting kicks in after the threshold

Q60. Create a security headers checklist with at least 15 items. Mark which ones helmet handles automatically vs which need manual configuration.


Cross-Topic Challenges (Q61-Q65)

Q61. Design a complete REST API for a blog platform:

  • Resources: users, posts, comments, tags
  • Include proper URL structure, HTTP methods, status codes
  • Add versioning (v1)
  • List what validations each endpoint needs

Q62. You receive a bug report: "Our API sometimes returns 500 errors when users submit forms." Walk through a systematic debugging approach using status codes, validation, and error handling.

Q63. A client reports that your API is "slow and sometimes returns errors." Design a rate limiting and caching strategy that balances performance with security.

Q64. Full coding project: Build a complete REST API for a task management app with:

  • User registration/login with validation
  • CRUD for tasks (with ownership checks)
  • API versioning (v1)
  • Rate limiting, helmet, CORS
  • Consistent error responses
  • Postman collection (export as JSON)

Q65. Review this Express route and list every security/validation issue you can find:

app.post('/api/users', async (req, res) => {
  const user = await User.create(req.body);
  res.json({ password: user.password, ...user.toObject() });
});

Answer Hints (Short)

QHint
Q3Code on Demand is the optional constraint
Q6GET /api/users, DELETE /api/users/42, PATCH /api/users/42, POST /api/users
Q14URL path versioning; GitHub, Stripe, Twitter
Q30401 = who are you? 403 = you can't do this
Q31422 when JSON is valid but business rules fail
Q44.parse() throws, .safeParse() returns result object
Q54JWTs in headers are not auto-sent by browsers (unlike cookies)
Q56Default has no limit — attackers can send huge payloads to exhaust memory
Q65No validation, no auth, exposes password, trusts req.body entirely

<- Back to 3.9 -- REST API Development (README)