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:
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
Use appropriate status codes
201 Createdfor POST200 OKfor GET/PUT/PATCH204 No Contentfor DELETE404 Not Foundwhen resource doesn't exist422 Unprocessable Entityfor validation errors
Return the created/updated resource
Use specific routes before generic ones
Include metadata in lists
Locationheader on created resources
β Avoid
DELETE returning 200 with deleted resource
GET modifying data
ID fields in POST body
Next Steps
Pagination How-to - Implement pagination
Authentication Mock - Simulate authentication
Error Handling - Error patterns
HTTP Methods - Methods reference
See Also
Your First Mock - Initial tutorial
Dynamic Responses - Dynamic responses
REST API Example - Complete example
Last updated
Was this helpful?