Skip to main content

API Design Principles

Guidelines for designing consistent, intuitive APIs in CORTEX.

RESTful Conventions

Resource Naming

PatternExampleDescription
Collection/usersList of resources
Item/users/:idSingle resource
Sub-resource/users/:id/rolesRelated resources
Action/users/:id/suspendNon-CRUD action

HTTP Methods

MethodUsageExample
GETRead resource(s)GET /users
POSTCreate resourcePOST /users
PATCHPartial updatePATCH /users/:id
PUTFull replacePUT /users/:id
DELETERemove resourceDELETE /users/:id

Status Codes

CodeUsage
200 OKSuccessful GET, PATCH, PUT
201 CreatedSuccessful POST
204 No ContentSuccessful DELETE
400 Bad RequestValidation error
401 UnauthorizedAuthentication required
403 ForbiddenPermission denied
404 Not FoundResource not found
409 ConflictDuplicate resource
429 Too ManyRate limited
500 InternalServer error

Request/Response Format

Request Body

{
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe"
}
  • Use camelCase for field names
  • Omit null/undefined optional fields
  • Use ISO 8601 for dates

Response Body

Single Resource

{
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe",
"createdAt": "2024-01-15T10:30:00.000Z"
}

Collection

{
"data": [
{ "id": "...", "email": "..." },
{ "id": "...", "email": "..." }
],
"pagination": {
"total": 100,
"page": 1,
"limit": 20,
"totalPages": 5
}
}

Pagination

Query Parameters

ParameterDefaultMaxDescription
page1-Page number
limit20100Items per page

Example

GET /users?page=2&limit=50

Response

{
"data": [...],
"pagination": {
"total": 150,
"page": 2,
"limit": 50,
"totalPages": 3,
"hasNext": true,
"hasPrev": true
}
}

Filtering & Sorting

Filtering

GET /users?status=ACTIVE&search=john
GET /audit-logs?action=CREATE&startDate=2024-01-01

Sorting

GET /users?sortBy=createdAt&sortOrder=desc

Error Format

Follow RFC 7807 Problem Details:

{
"type": "https://api.cortex.purplelab.ai/errors/validation-error",
"title": "Validation Error",
"status": 400,
"detail": "Email is required",
"instance": "/users",
"errors": [
{ "field": "email", "message": "is required" }
]
}

Versioning

URL Versioning (Current)

/api/v1/users
/api/v2/users

Guidelines

  • Major version changes for breaking changes
  • Maintain backward compatibility when possible
  • Deprecate before removing

Security

Authentication

All endpoints (except login/register) require Bearer token:

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Tenant Isolation

Resources are automatically scoped to the authenticated user's tenant.

Rate Limiting

Include rate limit headers in responses:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1705312500

Documentation

Every endpoint must have:

  1. Summary — One-line description
  2. Description — Detailed explanation
  3. Parameters — All query/path params
  4. Request Body — With examples
  5. Responses — All possible responses
  6. Errors — Common error cases

Swagger Decorators

@ApiOperation({
summary: 'Create user',
description: 'Creates a new user in the current tenant.',
})
@ApiBody({ type: CreateUserDto })
@ApiResponse({ status: 201, type: UserDto })
@ApiResponse({ status: 400, description: 'Validation error' })
@ApiResponse({ status: 409, description: 'Email already exists' })
@Post()
create(@Body() dto: CreateUserDto) {
return this.userService.create(dto);
}

Idempotency

Safe Methods

GET, HEAD, OPTIONS are safe and idempotent.

Idempotent Methods

PUT, DELETE should be idempotent.

POST Idempotency

For critical operations, support idempotency keys:

POST /payments
Idempotency-Key: abc123

# Second request with same key returns cached result

Best Practices Checklist

  • Use plural nouns for resources
  • Use HTTP methods correctly
  • Return appropriate status codes
  • Include pagination for lists
  • Validate all input
  • Return consistent error format
  • Document all endpoints
  • Include examples in docs
  • Version the API
  • Implement rate limiting