How do I handle edge cases in a CRUD API?
Not found: throw new ApiError(404, 'Resource not found'). Not authorized: compare the resource's owner to req.user.userId; throw 403 if they do not match. Validation: the validate middleware handles it. Duplicate: catch the 11000 error and return 409.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in The Thought Process for Writing a CRUD API
Identify the resource, define the schema, list the endpoints, write validation schemas, write controller functions, write the router, mount it, handle edge cases (not found, not authorized, duplicate), test, and document. Repeat for each resource.
GET /resource (list), POST /resource (create), GET /resource/:id (read), PATCH /resource/:id (update), DELETE /resource/:id (delete). Use plural nouns for the path. Version with /api/v1.
Validation is part of the API contract. Writing the schema first forces you to think about what input is valid. The controller then only runs with valid input. Order: schema, validation, controller, router, mount.
Still have questions?
Browse all our FAQs or reach out to our support team
