CRUD Operations

Learn how to implement complete CRUD operations (Create, Read, Update, Delete) with moclojer. Practical guide with tested examples.

This guide shows how to implement a complete RESTful API with all CRUD operations using moclojer. You'll learn the correct patterns for each operation and how to structure your responses.

What Are CRUD Operations?

CRUD is an acronym for the four basic data persistence operations:

Operation
HTTP Method
Action
Example

Create

POST

Create new resource

POST /users

Read

GET

Read resource(s)

GET /users, GET /users/1

Update

PUT/PATCH

Update resource

PUT /users/1, PATCH /users/1

Delete

DELETE

Remove resource

DELETE /users/1

Example API: Task Management System

Let's create a complete task management API with all CRUD operations.

Task Structure

{
  "id": 1,
  "title": "Buy milk",
  "description": "Go to the store and buy 2L of milk",
  "completed": false,
  "priority": "medium",
  "createdAt": "2024-01-15T10:00:00Z",
  "updatedAt": "2024-01-15T10:00:00Z"
}

CREATE - Create Resources

POST - Create New Task

Test:

Response (201 Created):

Required Field Validation

Note: In real production, you would validate the received JSON. In mocks, you can create specific endpoints to simulate errors.


READ - Read Resources

GET - List All Tasks

Test:

GET with Pagination

Test:

GET - Get Specific Task

Test:

GET - Task Not Found

Test:

GET with Filters

Test:


UPDATE - Update Resources

PUT - Replace Complete Task

PUT replaces the entire resource - all fields must be sent.

Test:

PATCH - Partial Update

PATCH updates only specific fields - send only what changed.

Test (update only completed):

Test (update title and priority):

Mark Task as Complete (Custom Action)

Test:

Update Validation Error


DELETE - Remove Resources

DELETE - Remove Task

Test:

DELETE with Confirmation (alternative)

Some prefer to return 200 with message:

Test:

DELETE - Task Not Found

Bulk DELETE (Clear Completed)

Test:


Complete API: Single File

Here's the complete tasks-api.yml file with all CRUD operations:


Testing the Complete API

Complete Test Script

Save as test-crud.sh, give permission and run:


Best Practices

βœ… Do

  1. Use appropriate status codes

    • 201 Created for POST

    • 200 OK for GET/PUT/PATCH

    • 204 No Content for DELETE

    • 404 Not Found when resource doesn't exist

    • 422 Unprocessable Entity for validation errors

  2. Return the created/updated resource

  3. Use specific routes before generic ones

  4. Include metadata in lists

  5. Location header on created resources

❌ Avoid

  1. DELETE returning 200 with deleted resource

  2. GET modifying data

  3. ID fields in POST body


Next Steps

See Also

Last updated

Was this helpful?