CRUD Operations: Building the Core of Any REST API
CRUD operations, Create Read Update Delete, REST CRUD, data layer, repository pattern, input validation, ID generation
CRUD Operations: Building the Core of Any REST API
CRUD — Create, Read, Update, Delete — represents the four fundamental operations that any data-driven REST API must support. Every feature in a REST API, no matter how complex it appears on the surface, maps to one or more of these four operations. Mastering CRUD is the foundation of REST API development.
Create: POST /resources
The create operation accepts a JSON body with the new resource's data, validates it, persists it to the data store, and returns the created resource with its generated ID and a 201 status. The server generates the ID — never let clients specify IDs for new resources unless you have a specific reason to do so.
Read: GET /resources and GET /resources/:id
Reading has two forms: listing a collection and fetching a single resource. Collection endpoints should support filtering, sorting, and pagination via query parameters. Single-resource endpoints return 404 if the ID does not exist. Consider carefully what fields to expose — never return passwords, internal IDs, or sensitive computed fields.
Update: PUT /resources/:id and PATCH /resources/:id
Use PUT when the client sends a complete replacement of the resource. Use PATCH for partial updates. Both should validate input data, check that the resource exists (returning 404 if not), and check that the caller has permission to update it (returning 403 if not).
Delete: DELETE /resources/:id
The delete operation should verify the resource exists, check authorization, remove or soft-delete the record, and return 204 No Content. Soft delete (marking a record as deleted rather than removing it from the database) is preferred in production systems because it preserves audit trails and allows recovery.
Input Validation Is Not Optional
Every create and update operation must validate input before touching the database. Check for required fields, correct data types, valid formats (email, UUID, date), value constraints (minimum/maximum length, numeric ranges), and uniqueness constraints. Return a detailed error listing every validation failure — not just the first one.
