Skip to main content

CRUD API Implementation Best Practices

This guide covers the standard conventions for implementing RESTful CRUD APIs in uc-enterprise-core, including request formats, response structures, pagination, filtering, and error handling.


Table of Contents​


Routing Conventions​

Follow RESTful resource naming with consistent HTTP method semantics:

MethodPathAction
GET/resourceList all (paginated)
GET/resource/:idGet single record
POST/resourceCreate new record
PUT/resource/:idFull update
PATCH/resource/:idPartial update
DELETE/resource/:idDelete record

Rules:

  • Use plural nouns for resource names (/users, /organizations, /calls)
  • Use kebab-case for multi-word resources (/call-segments, /active-calls)
  • Never use verbs in the path — the HTTP method is the verb
  • Nest resources when there is a clear parent–child relationship (/organizations/:orgId/users)

Request Format​

Headers​

All API requests must include:

Content-Type: application/json
Authorization: Bearer <token>

Create (POST)​

POST /api/v1/organizations
Content-Type: application/json

{
"organizationName": "Acme Corp",
"email": "admin@acme.com",
"phone": "+94771234567",
"countryId": 1,
"isActive": true
}

Update (PUT / PATCH)​

PUT /api/v1/organizations/42
Content-Type: application/json

{
"organizationName": "Acme Corporation",
"email": "info@acme.com"
}

Delete (DELETE)​

DELETE /api/v1/organizations/42

Response Format​

All API responses follow a consistent envelope structure.

Single Record Response​

{
"success": true,
"data": {
"id": 42,
"organizationName": "Acme Corp",
"email": "admin@acme.com",
"isActive": true,
"createdAt": "2026-09-01T08:00:00.000Z",
"updatedAt": "2026-09-18T10:30:00.000Z"
},
"message": "Record retrieved successfully"
}

List Response (with Pagination)​

{
"data": [
{
"id": 1,
"organizationName": "Acme Corp",
"email": "admin@acme.com",
"isActive": true,
"createdAt": "2026-09-01T08:00:00.000Z"
},
{
"id": 2,
"organizationName": "Globex Inc",
"email": "info@globex.com",
"isActive": false,
"createdAt": "2026-09-05T09:15:00.000Z"
}
],
"pagination": {
"currentPage": 1,
"pageSize": 10,
"totalRecords": 45,
"totalPages": 5
}
}

Create / Update Success Response​

{
"success": true,
"data": {
"id": 43,
"organizationName": "New Org",
"createdAt": "2026-09-18T12:00:00.000Z"
},
"message": "Organization created successfully"
}

Delete Success Response​

{
"success": true,
"message": "Organization deleted successfully"
}

Pagination​

Pagination is controlled via query parameters on list endpoints.

Query Parameters​

ParameterTypeDefaultDescription
limitinteger10Number of records per page (max 100)
offsetinteger0Number of records to skip
sortBystringidField name to sort by
sortOrderstringDESCSort direction: ASC or DESC

Example Request​

GET /api/v1/organizations?limit=10&offset=0&sortBy=id&sortOrder=DESC

Pagination Response Object​

{
"data": [],
"pagination": {
"currentPage": 1,
"pageSize": 10,
"totalRecords": 0,
"totalPages": 0
}
}
FieldDescription
currentPageCurrent page number (1-based, derived from offset)
pageSizeNumber of items returned in this response
totalRecordsTotal number of matching records in the database
totalPagesTotal pages (Math.ceil(totalRecords / limit))

Computing currentPage​

const currentPage = Math.floor(offset / limit) + 1;
const totalPages = Math.ceil(totalRecords / limit);

Filtering & Sorting​

Filtering uses a rules-based query structure passed as URL-encoded query parameters.

Filter Structure​

filterQuery[rules][{index}][field] = <fieldName>
filterQuery[rules][{index}][operator] = <operator>
filterQuery[rules][{index}][value] = <value>

Multiple rules are combined with AND logic by default.

Full Example (Decoded)​

GET /api/v1/organizations
?limit=10
&offset=0
&sortBy=id
&sortOrder=DESC
&filterQuery[rules][0][field]=id
&filterQuery[rules][0][operator]=eq
&filterQuery[rules][0][value]=33
&filterQuery[rules][1][field]=organizationName
&filterQuery[rules][1][operator]=contains
&filterQuery[rules][1][value]=we

URL-Encoded Version​

limit=10&offset=0&sortBy=id&sortOrder=DESC&filterQuery%5Brules%5D%5B0%5D%5Bfield%5D=id&filterQuery%5Brules%5D%5B0%5D%5Boperator%5D=eq&filterQuery%5Brules%5D%5B0%5D%5Bvalue%5D=33&filterQuery%5Brules%5D%5B1%5D%5Bfield%5D=organizationName&filterQuery%5Brules%5D%5B1%5D%5Boperator%5D=contains&filterQuery%5Brules%5D%5B1%5D%5Bvalue%5D=we

Parsed Filter Object (Server-side)​

{
"rules": [
{ "field": "id", "operator": "eq", "value": "33" },
{ "field": "organizationName", "operator": "contains", "value": "we" }
]
}

Filter Operators Reference​

OperatorSQL EquivalentDescription
eq= valueExact match
neq!= valueNot equal
containsILIKE '%value%'Case-insensitive substring match
notContainsNOT ILIKE '%value%'Does not contain substring
startsWithILIKE 'value%'Starts with value
endsWithILIKE '%value'Ends with value
gt> valueGreater than
gte>= valueGreater than or equal
lt< valueLess than
lte<= valueLess than or equal
inIN (v1, v2, ...)Value is in a list
notInNOT IN (v1, v2, ...)Value is not in a list
isNullIS NULLField is null
isNotNullIS NOT NULLField is not null
betweenBETWEEN v1 AND v2Value is within a range

Using in Operator​

Pass multiple values as a comma-separated string:

filterQuery[rules][0][field]=status
filterQuery[rules][0][operator]=in
filterQuery[rules][0][value]=active,pending,review

Using between Operator​

Pass two values separated by a comma:

filterQuery[rules][0][field]=createdAt
filterQuery[rules][0][operator]=between
filterQuery[rules][0][value]=2026-01-01,2026-09-18

Error Handling​

Error Response Format​

{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "organizationName is required",
"details": [
{
"field": "organizationName",
"message": "This field is required"
}
]
}
}

Standard HTTP Status Codes​

StatusCodeUsage
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST (record created)
204No ContentSuccessful DELETE
400Bad RequestValidation errors, malformed request body
401UnauthorizedMissing or invalid authentication token
403ForbiddenAuthenticated but insufficient permissions
404Not FoundResource does not exist
409ConflictDuplicate record / unique constraint violated
422Unprocessable EntityBusiness logic validation failure
500Internal Server ErrorUnexpected server error

Complete Examples​

Example 1 — List with Pagination Only​

GET /api/v1/users?limit=20&offset=20&sortBy=createdAt&sortOrder=ASC

Response:

{
"data": [
{
"id": 21,
"firstName": "Alice",
"lastName": "Smith",
"email": "alice@example.com"
},
{
"id": 22,
"firstName": "Bob",
"lastName": "Jones",
"email": "bob@example.com"
}
],
"pagination": {
"currentPage": 2,
"pageSize": 20,
"totalRecords": 58,
"totalPages": 3
}
}

Example 2 — Filtered + Sorted List​

GET /api/v1/users
?limit=10&offset=0&sortBy=lastName&sortOrder=ASC
&filterQuery[rules][0][field]=isActive
&filterQuery[rules][0][operator]=eq
&filterQuery[rules][0][value]=true
&filterQuery[rules][1][field]=firstName
&filterQuery[rules][1][operator]=contains
&filterQuery[rules][1][value]=ali

Response:

{
"data": [
{ "id": 5, "firstName": "Alicia", "lastName": "Brown", "isActive": true },
{ "id": 9, "firstName": "Ali", "lastName": "Hassan", "isActive": true }
],
"pagination": {
"currentPage": 1,
"pageSize": 10,
"totalRecords": 2,
"totalPages": 1
}
}

Example 3 — Empty Result​

GET /api/v1/organizations?limit=10&offset=0
&filterQuery[rules][0][field]=id
&filterQuery[rules][0][operator]=eq
&filterQuery[rules][0][value]=9999

Response:

{
"data": [],
"pagination": {
"currentPage": 1,
"pageSize": 10,
"totalRecords": 0,
"totalPages": 0
}
}

Example 4 — Create Organization​

Request:

POST /api/v1/organizations
Content-Type: application/json

{
"organizationName": "Uniconnect Labs",
"email": "hello@uniconnect.io",
"phone": "+94112345678",
"countryId": 144,
"isActive": true
}

Response 201 Created:

{
"success": true,
"data": {
"id": 101,
"organizationName": "Uniconnect Labs",
"email": "hello@uniconnect.io",
"phone": "+94112345678",
"countryId": 144,
"isActive": true,
"createdAt": "2026-09-18T09:00:00.000Z",
"updatedAt": "2026-09-18T09:00:00.000Z"
},
"message": "Organization created successfully"
}

Example 5 — Validation Error​

Request:

POST /api/v1/organizations
Content-Type: application/json

{
"email": "not-an-email"
}

Response 400 Bad Request:

{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "organizationName",
"message": "organizationName is required"
},
{ "field": "email", "message": "Must be a valid email address" }
]
}
}

Summary Checklist​

  • Use plural nouns and kebab-case for route paths
  • Always return data + pagination on list endpoints
  • Always return success, data, message on single-record endpoints
  • Use limit / offset for pagination (not page)
  • Expose totalRecords and totalPages in every paginated response
  • Use the filterQuery[rules] structure for all filter parameters
  • Use appropriate HTTP status codes (201 for create, 204 for delete)
  • Wrap errors in { success: false, error: { code, message, details } }
  • Whitelist allowed sort fields server-side to prevent injection
  • Validate filter fields against an allowed-fields list before querying