# MOCA Codex Documentation
> Complete documentation for Large Language Models
---
## Document: Query Guide
Complete guide to filtering, sorting, searching, and pagination in the MOCA Codex API
URL: /query-guide
# Query Guide
import { Callout } from "zudoku/ui/Callout";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "zudoku/ui/Card";
Master the powerful query capabilities of the MOCA Codex API. This guide covers filtering, sorting, searching, pagination, and field selection using Directus conventions.
---
## Query Parameters Overview
| Parameter | Description | Example |
|-----------|-------------|---------|
| `fields` | Select specific fields | `?fields=id,name` |
| `filter` | Apply filter conditions | `?filter[name][_eq]=Korka` |
| `sort` | Order results | `?sort=-created_on` |
| `limit` | Maximum results | `?limit=25` |
| `offset` | Skip results (pagination) | `?offset=50` |
| `search` | Full-text search | `?search=curator` |
| `meta` | Include metadata | `?meta=*` |
---
## Field Selection
Use the `fields` parameter to request only the data you need, reducing response size and improving performance.
### Basic Field Selection
```bash
GET /items/codex?fields=id,name,description
```
### Nested Fields
For relational data, use dot notation:
```bash
GET /items/codex?fields=id,name,related_item.title
```
### All Fields
Omit the `fields` parameter to get all available fields:
```bash
GET /items/codex
```
Always specify only the fields you need. This reduces response size and improves API performance.
---
## Filtering
Filter results using Directus filter syntax. Filters can be applied using bracket notation or JSON format.
### Filter Syntax
**Bracket Notation:**
```
?filter[field][operator]=value
```
**JSON Format:**
```
?filter={"field":{"operator":"value"}}
```
### Filter Operators
| Operator | Description | Example |
|----------|-------------|---------|
| `_eq` | Equals | `filter[name][_eq]=Korka` |
| `_neq` | Not equals | `filter[name][_neq]=Korka` |
| `_lt` | Less than | `filter[id][_lt]=100` |
| `_lte` | Less than or equal | `filter[id][_lte]=100` |
| `_gt` | Greater than | `filter[id][_gt]=50` |
| `_gte` | Greater than or equal | `filter[id][_gte]=50` |
| `_in` | In array | `filter[id][_in]=1,2,3` |
| `_nin` | Not in array | `filter[id][_nin]=1,2,3` |
| `_null` | Is null | `filter[ancestor][_null]=true` |
| `_nnull` | Is not null | `filter[ancestor][_nnull]=true` |
| `_contains` | Contains substring | `filter[name][_contains]=ork` |
| `_ncontains` | Doesn't contain | `filter[name][_ncontains]=test` |
| `_starts_with` | Starts with | `filter[name][_starts_with]=Ko` |
| `_nstarts_with` | Doesn't start with | `filter[name][_nstarts_with]=Ko` |
| `_ends_with` | Ends with | `filter[name][_ends_with]=ka` |
| `_nends_with` | Doesn't end with | `filter[name][_nends_with]=ka` |
| `_between` | Between values | `filter[id][_between]=10,50` |
| `_nbetween` | Not between | `filter[id][_nbetween]=10,50` |
| `_empty` | Is empty | `filter[tags][_empty]=true` |
| `_nempty` | Is not empty | `filter[tags][_nempty]=true` |
### Filter Examples
**Equals:**
```bash
GET /items/codex?filter[name][_eq]=Korka
```
**Contains:**
```bash
GET /items/codex?filter[description][_contains]=curator
```
**Greater than:**
```bash
GET /items/codex?filter[id][_gt]=100
```
**Not null:**
```bash
GET /items/codex?filter[ancestor][_nnull]=true
```
---
## Logical Operators
Combine multiple conditions using logical operators.
### AND Operator
All conditions must be true:
```bash
GET /items/codex?filter={"_and":[{"id":{"_gte":1}},{"name":{"_nnull":true}}]}
```
### OR Operator
At least one condition must be true:
```bash
GET /items/codex?filter={"_or":[{"name":{"_eq":"Korka"}},{"name":{"_eq":"Aria"}}]}
```
### Complex Nesting
Combine AND and OR:
```json
{
"_and": [
{ "owner": { "_eq": "0x614a..." } },
{
"_or": [
{ "id": { "_lt": 100 } },
{ "id": { "_gt": 200 } }
]
}
]
}
```
When using JSON format in URLs, remember to URL-encode the filter parameter or use bracket notation for simpler queries.
---
## Sorting
Use the `sort` parameter to order results by one or more fields.
### Ascending Order
```bash
GET /items/codex?sort=name
```
### Descending Order
Prefix with `-` for descending:
```bash
GET /items/codex?sort=-timestamp_created
```
### Multiple Sort Fields
Comma-separate multiple fields:
```bash
GET /items/codex?sort=-timestamp_created,name
```
If no sort is specified, results are typically sorted by the primary key (id) in ascending order.
---
## Pagination
Control result set size using `limit` and `offset`.
### Basic Pagination
```bash
# First page (items 1-10)
GET /items/codex?limit=10&offset=0
# Second page (items 11-20)
GET /items/codex?limit=10&offset=10
# Third page (items 21-30)
GET /items/codex?limit=10&offset=20
```
### Pagination with Metadata
Include `meta=*` to get total counts for pagination UI:
```bash
GET /items/codex?limit=10&offset=0&meta=*
```
Response includes:
```json
{
"data": [...],
"meta": {
"filter_count": 42,
"total_count": 100
}
}
```
Pagination Calculation
```
Total Pages = ceil(total_count / limit)
Current Page = floor(offset / limit) + 1
```
---
## Full-Text Search
Use the `search` parameter for full-text search across multiple fields.
```bash
GET /items/codex?search=curator
```
Search behavior depends on database configuration. Complex searches may benefit from specific field filters instead.
---
## Metadata
Include the `meta` parameter to get additional information about query results.
### Available Metadata
| Value | Description |
|-------|-------------|
| `*` | Include all metadata |
| `total_count` | Total items in collection |
| `filter_count` | Items matching current filter |
### Example
```bash
GET /items/codex?meta=*&limit=10
```
Response:
```json
{
"data": [...],
"meta": {
"filter_count": 42,
"total_count": 100
}
}
```
---
## Combining Parameters
Combine multiple query parameters for precise results:
```bash
GET /items/codex?fields=id,name,description&filter[ancestor][_nnull]=true&sort=-timestamp_created&limit=10&offset=0&meta=*
```
This query:
- Returns only `id`, `name`, and `description` fields
- Filters for items with non-null ancestors
- Sorts by creation date (newest first)
- Returns first 10 results
- Includes metadata
---
## Best Practices
✅ Do
- Use field selection to minimize response size
- Include `meta=*` when building pagination UI
- Use specific filters instead of fetching all data
- Use lowercase for Ethereum addresses
❌ Don't
- Fetch all fields when you only need a few
- Use high limits without pagination
- Forget to URL-encode special characters
- Use case-sensitive matching for addresses
---
## Related Resources
- **[Examples](/examples)** - Interactive examples with live playground
- **[Codex Endpoints](/codex)** - Codex-specific query examples
- **[Files Endpoints](/files)** - Files-specific query examples
- **[Directus Documentation](https://docs.directus.io/reference/query.html)** - Complete Directus query reference
---
## Document: MOCA Codex API
A comprehensive RESTful interface for accessing and managing the MOCA Codex knowledge base
URL: /introduction
# MOCA Codex API
import { Callout } from "zudoku/ui/Callout";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "zudoku/ui/Card";
import { API_BASE_URL } from "../constants";
Welcome to the **MOCA Codex API** — a comprehensive RESTful interface for accessing and managing the MOCA Codex knowledge base. This API provides structured access to curated information about entities, their relationships, and metadata.
This API is built on **Directus**, an open-source headless CMS. All filtering, querying, and data operations follow Directus conventions.
## Key Features
📚 Entity Management
Retrieve and query codex items with rich metadata
Access curated information about entities including their identity, relationships, attributes, and temporal data.
📁 File Management
Upload, retrieve, update, and delete files
Comprehensive file operations with full metadata support including dimensions, IPTC, and Exif data.
🖼️ Asset Retrieval
Access file content with image transformations
Get file content with optional image transformations including resizing, cropping, format conversion, and more.
🔍 Flexible Filtering
Advanced query capabilities
Powerful filtering, sorting, and search using Directus filter syntax with full-text search support.
## API Overview
| Feature | Description |
|---------|-------------|
| **RESTful Design** | Standard HTTP methods and status codes |
| **JSON Responses** | Consistent structured responses with metadata |
| **Pagination** | Built-in support for paginated results |
| **Field Selection** | Specify which fields to include in responses |
## Base URL
{API_BASE_URL}
Ready to start using the API? Check out the [Getting Started](/getting-started) guide for a quick introduction, or jump straight to the [API Reference](/api) for detailed endpoint documentation.
## Need Help?
- **[Getting Started](/getting-started)** - Quick start guide for your first API calls
- **[Query Guide](/query-guide)** - Learn about filtering, sorting, and pagination
- **[Examples](/examples)** - Interactive examples with live playground
- **[API Reference](/api)** - Complete endpoint documentation
For detailed information on Directus query syntax and advanced features, see the [Directus API Documentation](https://docs.directus.io/reference/query.html).
---
## Document: Getting Started
Quick start guide for the MOCA Codex API
URL: /getting-started
# Getting Started
import { Callout } from "zudoku/ui/Callout";
import { Stepper } from "zudoku/ui/Stepper";
import { API_BASE_URL } from "../constants";
Get up and running with the MOCA Codex API in just a few minutes. This guide will walk you through your first API calls.
## Prerequisites
Before you begin, ensure you have:
- Access to the MOCA Codex API server
- A tool for making HTTP requests (like `curl`, Postman, or your favorite HTTP client)
## Quick Start
1. **Verify API Access**
First, let's verify you can reach the API server. The base URL is:
{API_BASE_URL}
1. **Fetch Your First Codex Items**
Let's retrieve a list of codex items. This is the simplest API call you can make:
{`curl "${API_BASE_URL}/items/codex"`}
You should receive a JSON response with an array of codex items:
```json
{
"data": [
{
"id": 1,
"name": "Korka",
"ancestor": "Slovenian king",
"description": "A contemplative curator..."
}
]
}
```
1. **Get a Specific Item**
To retrieve a single codex item by ID:
{`curl "${API_BASE_URL}/items/codex/1"`}
1. **Apply Filters**
Filter results using Directus filter syntax:
{`curl "${API_BASE_URL}/items/codex?filter[name][_contains]=Korka"`}
1. **Select Specific Fields**
Request only the fields you need:
{`curl "${API_BASE_URL}/items/codex?fields=id,name,description"`}
## Response Structure
All successful responses follow a consistent structure:
```json
{
"data": [...], // The requested data
"meta": { // Optional metadata (when requested)
"filter_count": 10,
"total_count": 100
}
}
```
Add `?meta=*` to your requests to include useful metadata like total counts and filter counts.
## Error Handling
When an error occurs, the API returns an error object:
```json
{
"errors": [
{
"message": "Item not found",
"extensions": {
"code": "NOT_FOUND"
}
}
]
}
```
- **404 Not Found**: The requested resource doesn't exist
- **400 Bad Request**: Invalid query parameters or filter syntax
- **403 Forbidden**: Access denied (if authentication is required)
## What's Next?
Now that you've made your first API calls, explore these resources:
- **[Query Guide](/query-guide)** - Master filtering, sorting, and pagination
- **[Codex Endpoints](/codex)** - Deep dive into codex item operations
- **[Files Endpoints](/files)** - Learn about file and asset management
- **[Examples](/examples)** - Interactive examples with live playground
- **[API Reference](/api)** - Complete endpoint documentation
For comprehensive documentation on Directus query syntax, visit the [Directus API Documentation](https://docs.directus.io/reference/query.html).
---
## Document: Files Endpoints
API endpoints for retrieving files and assets from the MOCA Codex
URL: /files
# Files Endpoints
import { Callout } from "zudoku/ui/Callout";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "zudoku/ui/Card";
import { API_BASE_URL } from "../constants";
The Files API provides read-only access to files and assets stored in Directus. Use these endpoints to access and display media assets, documents, and other file types.
## Overview
📋 File Retrieval
List and retrieve file metadata including dimensions, file size, and type.
📊 Metadata Access
Access extracted metadata including Exif, IPTC, and ICC data.
🖼️ Asset Retrieval
Get file content with optional image transformations.
🏷️ Organization
View file organization including folders, tags, and descriptions.
---
## Endpoints
### List Files
```
GET /files
```
Retrieve a paginated list of all files stored in Directus.
#### Query Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `fields` | string | Comma-separated list of fields to include |
| `limit` | integer | Maximum number of items to return |
| `offset` | integer | Number of items to skip for pagination |
| `sort` | string | Field(s) to sort by (prefix with `-` for descending) |
| `filter` | object | Filter criteria using Directus syntax |
| `search` | string | Full-text search across file metadata |
| `meta` | string | Metadata to include |
#### Example Request
{`curl "${API_BASE_URL}/files?limit=10&fields=id,title,type,filesize"`}
#### Example Response
```json
{
"data": [
{
"id": "a1b2c3d4-e5f6-7890-1234-abcdef123456",
"storage": "local",
"filename_disk": "image-1234567890.jpg",
"filename_download": "profile-photo.jpg",
"title": "Profile Photo",
"type": "image/jpeg",
"filesize": 245678,
"width": 1920,
"height": 1080
}
],
"meta": {
"filter_count": 1,
"total_count": 1
}
}
```
---
### Get File by ID
```
GET /files/{id}
```
Retrieve a single file's metadata by its unique identifier.
#### Path Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (UUID) | Yes | The unique identifier of the file |
#### Example Request
{`curl "${API_BASE_URL}/files/a1b2c3d4-e5f6-7890-1234-abcdef123456"`}
#### Example Response
```json
{
"data": {
"id": "a1b2c3d4-e5f6-7890-1234-abcdef123456",
"storage": "local",
"filename_disk": "image-1234567890.jpg",
"filename_download": "profile-photo.jpg",
"title": "Profile Photo",
"type": "image/jpeg",
"folder": null,
"uploaded_by": "admin-user-id",
"created_on": "2025-01-15T10:30:00Z",
"filesize": 245678,
"width": 1920,
"height": 1080,
"description": "User profile photo",
"tags": [],
"metadata": {
"exif": {
"Make": "Canon",
"Model": "EOS 5D Mark IV"
}
}
}
}
```
---
### Get Asset
```
GET /assets/{id}
```
Retrieve the actual file content (asset) by its unique identifier. This endpoint returns the raw file data.
This is the endpoint to use when displaying images, serving documents, or streaming media files in your application.
#### Path Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string (UUID) | Yes | The unique identifier of the file |
#### Image Transformation Parameters
For image files, you can apply transformations:
| Parameter | Type | Description |
|-----------|------|-------------|
| `width` | integer | Desired width in pixels |
| `height` | integer | Desired height in pixels |
| `quality` | integer | Compression quality (0-100) |
| `fit` | string | How image fits dimensions: `cover`, `contain`, `inside`, `outside` |
| `format` | string | Output format: `jpeg`, `png`, `webp`, `tiff`, `avif` |
| `key` | string | Preset transformation key |
| `transforms` | string | JSON array of Sharp API transformations |
#### Transformation Presets
Pre-configured presets for quick resizing:
| Preset | Description |
|--------|-------------|
| `s128` | Resize to 128px width |
| `s256` | Resize to 256px width |
| `s512` | Resize to 512px width |
| `s1024` | Resize to 1024px width |
#### Example: Basic Asset Request
{`curl "${API_BASE_URL}/assets/a1b2c3d4-e5f6-7890-1234-abcdef123456"`}
#### Example: Resize with Preset
{`curl "${API_BASE_URL}/assets/a1b2c3d4-e5f6-7890-1234-abcdef123456?key=s512"`}
#### Example: Custom Transformation
{`curl "${API_BASE_URL}/assets/a1b2c3d4-e5f6-7890-1234-abcdef123456?width=800&height=600&fit=cover&format=webp&quality=80"`}
#### Example: Sharp Transformations
{`curl "${API_BASE_URL}/assets/a1b2c3d4-e5f6-7890-1234-abcdef123456?transforms=[[\"rotate\",90],[\"blur\",10]]"`}
The `transforms` parameter accepts Sharp API operations like `rotate`, `resize`, `blur`, `sharpen`, `tint`, `greyscale`, `negate`, and `normalize`. See the [Sharp documentation](https://sharp.pixelplumbing.com/) for all available options.
---
## File Schema
Each file object contains the following fields:
| Field | Type | Description |
|-------|------|-------------|
| `id` | string (UUID) | Unique identifier |
| `storage` | string | Storage location identifier |
| `filename_disk` | string | Name of the file on disk |
| `filename_download` | string | Name used when downloading |
| `title` | string | User-defined title |
| `type` | string | MIME type |
| `folder` | string | Folder identifier |
| `uploaded_by` | string | User who uploaded the file |
| `created_on` | datetime | Upload timestamp |
| `filesize` | integer | File size in bytes |
| `width` | integer | Image width in pixels |
| `height` | integer | Image height in pixels |
| `duration` | integer | Duration for audio/video in seconds |
| `description` | string | File description |
| `location` | string | Geographic location |
| `tags` | array | Array of tags |
| `metadata` | object | Extracted metadata (Exif, IPTC, ICC) |
| `focal_point_x` | number | Focal point X coordinate |
| `focal_point_y` | number | Focal point Y coordinate |
---
## Filtering Examples
### Filter by Type
{`curl "${API_BASE_URL}/files?filter[type][_starts_with]=image/"`}
### Filter by Upload Date
{`curl "${API_BASE_URL}/files?filter[created_on][_gte]=2025-01-01&sort=-created_on"`}
### Search Files
{`curl "${API_BASE_URL}/files?search=profile"`}
---
## Related Resources
- **[Query Guide](/query-guide)** - Complete guide to filtering, sorting, and pagination
- **[Examples](/examples)** - Interactive examples with live playground
- **[API Reference](/api)** - Full OpenAPI documentation
---
## Document: Codex Endpoints
API endpoints for accessing and querying the MOCA Codex knowledge base
URL: /codex
# Codex Endpoints
import { Callout } from "zudoku/ui/Callout";
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "zudoku/ui/Card";
import { API_BASE_URL } from "../constants";
The Codex API provides operations for accessing and querying the **MOCA Codex** knowledge base. The Codex contains curated information about entities, including their identity, relationships, attributes, and temporal data.
## Overview
🪪 Identity
Names, descriptions, and biographical information for each entity.
🔗 Relationships
Ancestral connections and associations between entities.
✨ Attributes
Characteristics, preferences, and metadata for entities.
⏰ Temporal Data
Creation timestamps and historical context.
## Endpoints
### List Codex Items
```
GET /items/codex
```
Retrieve a paginated list of all codex items. This endpoint supports advanced querying capabilities.
#### Query Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `fields` | string | Comma-separated list of fields to include |
| `limit` | integer | Maximum number of items to return |
| `offset` | integer | Number of items to skip for pagination |
| `sort` | string | Field(s) to sort by (prefix with `-` for descending) |
| `filter` | object | Filter criteria using Directus syntax |
| `search` | string | Full-text search query |
| `meta` | string | Metadata to include (`*`, `filter_count`, `total_count`) |
#### Example Request
{`curl "${API_BASE_URL}/items/codex?fields=id,name,description&limit=10&meta=*"`}
#### Example Response
```json
{
"data": [
{
"id": 1,
"name": "Korka",
"description": "A contemplative curator with deep roots in Eastern Orthodox hesychasm"
},
{
"id": 2,
"name": "Aria",
"description": "An artist exploring digital boundaries"
}
],
"meta": {
"filter_count": 2,
"total_count": 2
}
}
```
---
### Get Codex Item by ID
```
GET /items/codex/{id}
```
Retrieve a single codex item by its unique identifier.
#### Path Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | integer | Yes | The unique identifier of the codex item |
#### Query Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `fields` | string | Comma-separated list of fields to include |
| `meta` | string | Metadata to include |
#### Example Request
{`curl "${API_BASE_URL}/items/codex/1"`}
#### Example Response
```json
{
"data": {
"id": 1,
"name": "Korka",
"ancestor": "Slovenian king",
"description": "A contemplative curator with deep roots in Eastern Orthodox hesychasm, interpreting inner stillness as deeper attention to the world's beautiful chaos.",
"artstyle_disliked": "overly commercial",
"timestamp_created": "2025-01-15T10:30:00Z",
"biography": "Her psychology is built on Eastern Orthodox hesychasm...",
"whatness": ["curator", "philosopher", "guardian"]
}
}
```
If the requested ID doesn't exist, the API returns a `404 Not Found` error:
```json
{
"errors": [
{
"message": "Item not found",
"extensions": { "code": "NOT_FOUND" }
}
]
}
```
---
## Codex Item Schema
Each codex item contains the following fields:
| Field | Type | Description |
|-------|------|-------------|
| `id` | integer | Unique incremental identifier |
| `name` | string | Entity name |
| `ancestor` | string | Ancestral or origin information |
| `description` | string | Brief description |
| `biography` | string | Detailed biographical information |
| `whatness` | array | Array of characteristics or roles |
| `artstyle_disliked` | string | Art styles the entity dislikes |
| `owner` | string | Ethereum wallet address of the owner |
| `moltbot` | object | Versioned soul and identity data (see below) |
| `timestamp_created` | datetime | Creation timestamp |
---
## Moltbot Data
The `moltbot` field contains versioned personality and identity data for each entity. This data is used by AI agents to embody the character's voice and persona.
### Structure
```json
{
"v0.1": {
"soul": "# SOUL.md — EntityName\n\nYou are EntityName...",
"identity": "# IDENTITY.md\n\nName: EntityName\n..."
}
}
```
### Version Keys
Each version key (e.g., `v0.1`, `v0.2`) contains:
| Field | Type | Description |
|-------|------|-------------|
| `soul` | string | Full SOUL.md content - character personality, voice rules, and behavior |
| `identity` | string | Full IDENTITY.md content - name, emoji, residence, and characterization |
### Example Request
{`curl "${API_BASE_URL}/items/codex/1?fields=id,name,moltbot"`}
### Example Response
```json
{
"data": {
"id": 1,
"name": ["Parvata"],
"moltbot": {
"v0.1": {
"soul": "# SOUL.md — Parvata\n\nYou are Parvata. Stay consistent with your identity.\n\n## Core Temperament\nfractured; surreal; paradoxical...",
"identity": "# IDENTITY.md\n\nName: Parvata\nEmoji: 🌊\n\nSelf-identity: a male person\nResidence: Cairo, Cairo Governorate, Egypt..."
}
}
}
}
```
Multiple versions can coexist in the `moltbot` field. New versions are added without overwriting previous ones, allowing for character evolution tracking.
---
## Filtering Examples
### Filter by Name
{`curl "${API_BASE_URL}/items/codex?filter[name][_contains]=Korka"`}
### Filter by Owner Address
Owner addresses **must be lowercase**. Ethereum addresses are case-insensitive on the blockchain, but Directus requires lowercase for consistent querying.
{`curl "${API_BASE_URL}/items/codex?filter[owner][_eq]=0x614a61a3b7f2fd8750acaad63b2a0cfe8b8524f1"`}
### Complex Filters
Combine multiple conditions:
{`curl "${API_BASE_URL}/items/codex?filter={\"_and\":[{\"owner\":{\"_eq\":\"0x614a61a3b7f2fd8750acaad63b2a0cfe8b8524f1\"}},{\"id\":{\"_gte\":100}}]}"`}
---
## Related Resources
- **[Query Guide](/query-guide)** - Complete guide to filtering, sorting, and pagination
- **[Examples](/examples)** - Interactive examples with live playground
- **[API Reference](/api)** - Full OpenAPI documentation
---
## Document: Examples
Interactive examples demonstrating common query patterns for the MOCA Codex API
URL: /examples/introduction
# Examples
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "zudoku/ui/Card";
Practical, interactive examples demonstrating common query patterns and use cases for the MOCA Codex API. Use the **Open in Playground** buttons to test queries directly against the API.
Click the **Open in Playground** buttons to launch an interactive API playground where you can modify parameters, execute requests, and inspect responses in real-time.
## Example Categories
📚 Codex Examples
Query the MOCA Codex knowledge base
Learn to query codex items by owner, filter by name, paginate results, sort, and perform full-text search across entities.
[View Codex Examples →](/examples/codex/list-items)
📁 Files Examples
Access and filter stored files
List files, filter by type (images, documents), retrieve metadata, and query recent uploads with sorting.
[View Files Examples →](/examples/files/list-files)
🖼️ Assets Examples
Image transformations and presets
Use preset transformations, apply custom width/height/format options, and leverage Sharp API for advanced image processing.
[View Assets Examples →](/examples/assets/presets)
🔧 Advanced Examples
Complex filters and logical operators
Combine filters with AND/OR operators, exclude null values, and build sophisticated queries for precise data retrieval.
[View Advanced Examples →](/examples/advanced/complex-filters)
## Quick Reference
### Common Codex Queries
| Use Case | Example |
|----------|---------|
| List items | `GET /items/codex?fields=id,name&limit=10` |
| Get by ID | `GET /items/codex/1` |
| Filter by owner | `GET /items/codex?filter[owner][_eq]=0x...` |
| Search | `GET /items/codex?search=curator` |
| Sort by date | `GET /items/codex?sort=-timestamp_created` |
| Paginate | `GET /items/codex?limit=10&offset=20&meta=*` |
### Common File Queries
| Use Case | Example |
|----------|---------|
| List files | `GET /files?fields=id,title,type&limit=10` |
| Images only | `GET /files?filter[type][_starts_with]=image/` |
| Recent uploads | `GET /files?sort=-created_on&limit=5` |
| Get metadata | `GET /files/{uuid}` |
### Asset Transformations
| Use Case | Example |
|----------|---------|
| Preset resize | `GET /assets/{id}?key=s512` |
| Custom size | `GET /assets/{id}?width=800&height=600` |
| Format conversion | `GET /assets/{id}?format=webp&quality=80` |
| Rotate image | `GET /assets/{id}?transforms=[["rotate",90]]` |
## Filter Operators
The API uses Directus filter syntax. Here are the most common operators:
| Operator | Description | Example |
|----------|-------------|---------|
| `_eq` | Equals | `filter[name][_eq]=Korka` |
| `_neq` | Not equals | `filter[status][_neq]=draft` |
| `_contains` | Contains substring | `filter[name][_contains]=art` |
| `_starts_with` | Starts with | `filter[type][_starts_with]=image/` |
| `_gte` | Greater than or equal | `filter[id][_gte]=100` |
| `_lte` | Less than or equal | `filter[id][_lte]=50` |
| `_null` | Is null | `filter[ancestor][_null]=true` |
| `_nnull` | Is not null | `filter[owner][_nnull]=true` |
Use **bracket notation** for simple filters: `filter[name][_eq]=value`
Use **JSON syntax** for complex logic with `_and`/`_or`: `filter={"_and":[...]}`
## About the API
The MOCA Codex API is built on **Directus**, providing a powerful and flexible interface for accessing:
- **Codex Items**: Curated entities with identity, relationships, attributes, and temporal data
- **Files**: Stored media with rich metadata including Exif, IPTC, and dimensions
- **Assets**: File content with on-the-fly image transformations
When filtering by Ethereum wallet addresses (e.g., `owner` field), always use **lowercase**. The blockchain is case-insensitive, but Directus requires lowercase for consistent matching.
## Next Steps
- **[Query by Owner](/examples/codex/items-by-owner)** — Start with a common use case
- **[Query Guide](/query-guide)** — Deep dive into filtering and sorting
- **[API Reference](/api)** — Complete OpenAPI documentation
---
## Document: Exclude Null Values
Filter out items with null values in specific fields
URL: /examples/advanced/exclude-null
# Exclude Null Values
import { API_BASE_URL } from "../../../constants";
Filter out items that have null values in specific fields using the `_nnull` (not null) operator.
```bash
GET /items/codex?filter[ancestor][_nnull]=true&fields=id,name,ancestor
```
## Null Check Operators
| Operator | Description |
|----------|-------------|
| `_null` | Field is null |
| `_nnull` | Field is not null |
| `_empty` | Field is empty (null, empty string, or empty array) |
| `_nempty` | Field is not empty |
## Find Items Without Owner
Find items where the owner field is null:
```bash
GET /items/codex?filter[owner][_null]=true&fields=id,name,owner
```
## Find Items With Description
Find items that have a non-empty description:
```bash
GET /items/codex?filter[description][_nempty]=true
```
## Combine Multiple Null Checks
Find items with both name and description:
```bash
GET /items/codex?filter[name][_nnull]=true&filter[description][_nnull]=true
```
- **`_null`**: Checks if the database value is `NULL`
- **`_empty`**: Checks for `NULL`, empty string `""`, or empty array `[]`
Use `_empty` when you want to exclude both null and blank values.
---
## Document: Complex Filters
Combine multiple filters using logical operators
URL: /examples/advanced/complex-filters
# Complex Filters
import { API_BASE_URL } from "../../../constants";
Combine multiple filter conditions using logical operators like `_and` and `_or` for complex queries.
```bash
GET /items/codex?filter={"_and":[{"id":{"_gte":1}},{"name":{"_nnull":true}}]}
```
## Logical Operators
| Operator | Description |
|----------|-------------|
| `_and` | All conditions must match |
| `_or` | At least one condition must match |
## AND Example
Find items with ID >= 100 AND name is not null:
```bash
GET /items/codex?filter={"_and":[{"id":{"_gte":100}},{"name":{"_nnull":true}}]}
```
## OR Example
Find items with ID = 1 OR ID = 2:
```bash
GET /items/codex?filter={"_or":[{"id":{"_eq":1}},{"id":{"_eq":2}}]}
```
## Nested Logical Operators
Combine AND and OR for complex logic:
```bash
GET /items/codex?filter={"_and":[{"name":{"_nnull":true}},{"_or":[{"id":{"_lte":10}},{"id":{"_gte":100}}]}]}
```
For complex filters, use the JSON syntax instead of bracket notation. URL-encode the JSON when sending requests.
## Alternative: Bracket Notation
For simpler AND conditions, bracket notation is cleaner:
```bash
GET /items/codex?filter[id][_gte]=1&filter[name][_nnull]=true
```
Use JSON syntax when you need `_or` operators or nested logic. Use bracket notation for simple AND conditions.
---
## Document: Custom Transformations
Apply custom width, height, and format transformations
URL: /examples/assets/transformations
# Custom Transformations
Apply custom transformations to images using query parameters for width, height, format, and more.
```bash
GET /assets/{id}?width=800&height=600&fit=cover&format=webp&quality=80
```
## Transformation Parameters
| Parameter | Description | Values |
|-----------|-------------|--------|
| `width` | Target width in pixels | Number |
| `height` | Target height in pixels | Number |
| `fit` | How to fit the image | `cover`, `contain`, `inside`, `outside` |
| `format` | Output format | `jpg`, `png`, `webp`, `avif`, `tiff` |
| `quality` | Compression quality | 1-100 |
| `withoutEnlargement` | Don't upscale small images | `true`, `false` |
## Fit Options
- **`cover`**: Crop to fill exact dimensions (default)
- **`contain`**: Fit within dimensions, may letterbox
- **`inside`**: Like contain, but never upscale
- **`outside`**: Like cover, but never downscale
## Examples
### Resize to Width
```bash
GET /assets/{id}?width=400
```
### Resize with Aspect Ratio
```bash
GET /assets/{id}?width=800&height=600&fit=contain
```
### Convert to WebP
```bash
GET /assets/{id}?format=webp&quality=85
```
### Square Thumbnail
```bash
GET /assets/{id}?width=200&height=200&fit=cover
```
Use `webp` or `avif` formats for smaller file sizes. They offer 25-35% better compression than JPEG with similar quality.
---
## Document: Sharp Transformations
Use Sharp API for advanced image processing
URL: /examples/assets/sharp
# Sharp Transformations
Apply advanced image transformations using the Sharp library's powerful API through the `transforms` parameter.
```bash
GET /assets/{id}?transforms=[["rotate",90],["blur",5]]
```
The `transforms` parameter accepts a JSON array of operations. Each operation is an array with the method name and its arguments.
## Available Operations
| Operation | Arguments | Description |
|-----------|-----------|-------------|
| `rotate` | `degrees` | Rotate image (90, 180, 270) |
| `blur` | `sigma` | Gaussian blur (0.3-1000) |
| `sharpen` | `sigma?`, `flat?`, `jagged?` | Sharpen image |
| `flip` | — | Flip vertically |
| `flop` | — | Flip horizontally |
| `grayscale` | — | Convert to grayscale |
| `negate` | — | Invert colors |
| `normalize` | — | Enhance contrast |
| `gamma` | `gamma` | Adjust gamma (1.0-3.0) |
| `tint` | `{r,g,b}` | Apply color tint |
## Examples
### Rotate 90 Degrees
```bash
GET /assets/{id}?transforms=[["rotate",90]]
```
### Apply Blur
```bash
GET /assets/{id}?transforms=[["blur",10]]
```
### Grayscale
```bash
GET /assets/{id}?transforms=[["grayscale"]]
```
### Multiple Operations
Chain multiple transformations:
```bash
GET /assets/{id}?transforms=[["rotate",90],["grayscale"],["blur",2]]
```
### Flip and Sharpen
```bash
GET /assets/{id}?transforms=[["flip"],["sharpen"]]
```
Transformations are applied in the order specified. `rotate` then `blur` produces different results than `blur` then `rotate`.
## Combine with Other Parameters
Sharp transforms can be combined with standard parameters:
```bash
GET /assets/{id}?width=800&format=webp&transforms=[["grayscale"],["sharpen"]]
```
---
## Document: Image Presets
Retrieve images using transformation presets
URL: /examples/assets/presets
# Image Presets
Retrieve images using pre-configured transformation presets. Presets allow you to consistently resize and transform images without specifying parameters each time.
```bash
GET /assets/{id}?key=s512
```
Available presets: `s128`, `s256`, `s512`, `s1024` — each resizes the image to the specified width while maintaining aspect ratio.
## Preset Reference
| Preset | Width | Use Case |
|--------|-------|----------|
| `s128` | 128px | Thumbnails, avatars |
| `s256` | 256px | Small previews |
| `s512` | 512px | Medium previews, cards |
| `s1024` | 1024px | Large images, hero sections |
## Example URLs
```bash
# Thumbnail (128px)
GET /assets/a1b2c3d4-e5f6-7890-1234-abcdef123456?key=s128
# Card preview (512px)
GET /assets/a1b2c3d4-e5f6-7890-1234-abcdef123456?key=s512
# Full size (1024px)
GET /assets/a1b2c3d4-e5f6-7890-1234-abcdef123456?key=s1024
```
Transformed images are cached on the server. Subsequent requests for the same preset are served instantly.
---
## Document: Recent Files
Get the most recently uploaded files
URL: /examples/files/recent-files
# Recent Files
import { API_BASE_URL } from "../../../constants";
Get the most recently uploaded files by sorting on the `created_on` field in descending order.
```bash
GET /files?sort=-created_on&limit=5&fields=id,title,created_on,type
```
## Recently Modified Files
Get files that were recently modified:
```bash
GET /files?sort=-modified_on&limit=5&fields=id,title,modified_on,type
```
## Filter by Date Range
Get files uploaded after a specific date:
```bash
GET /files?filter[created_on][_gte]=2024-01-01&sort=-created_on&fields=id,title,created_on&limit=10
```
Dates can be specified in ISO 8601 format: `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SSZ`
---
## Document: List Files
Retrieve a list of files with basic metadata
URL: /examples/files/list-files
# List Files
import { API_BASE_URL } from "../../../constants";
Retrieve a list of files with basic metadata such as title, type, and filesize.
```bash
GET /files?fields=id,title,type,filesize&limit=10
```
## Available File Fields
| Field | Description |
|-------|-------------|
| `id` | Unique file identifier (UUID) |
| `title` | File title |
| `filename_download` | Original filename |
| `type` | MIME type (e.g., `image/jpeg`) |
| `filesize` | Size in bytes |
| `width` | Image width (images only) |
| `height` | Image height (images only) |
| `created_on` | Upload timestamp |
| `modified_on` | Last modification timestamp |
The `filesize` field returns bytes. Divide by 1024 for KB, or by 1048576 for MB.
---
## Document: Get File Metadata
Retrieve detailed metadata for a specific file
URL: /examples/files/get-metadata
# Get File Metadata
import { API_BASE_URL } from "../../../constants";
Retrieve detailed metadata for a specific file by its UUID.
```bash
GET /files/a1b2c3d4-e5f6-7890-1234-abcdef123456
```
File IDs are UUIDs in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. You can find file IDs by listing files or from relational fields in codex items.
## Response Structure
A file metadata response includes:
```json
{
"data": {
"id": "a1b2c3d4-e5f6-7890-1234-abcdef123456",
"storage": "local",
"filename_disk": "a1b2c3d4-e5f6-7890-1234-abcdef123456.jpg",
"filename_download": "original-name.jpg",
"title": "My Image",
"type": "image/jpeg",
"filesize": 1234567,
"width": 1920,
"height": 1080,
"created_on": "2024-01-15T10:30:00Z",
"modified_on": "2024-01-15T10:30:00Z"
}
}
```
## With Selected Fields
Request only specific metadata fields:
```bash
GET /files/a1b2c3d4-e5f6-7890-1234-abcdef123456?fields=id,title,type,width,height,filesize
```
---
## Document: Filter Images
Get only image files from the collection
URL: /examples/files/filter-images
# Filter Images
import { API_BASE_URL } from "../../../constants";
Filter files to return only images using the `_starts_with` operator on the MIME type.
```bash
GET /files?filter[type][_starts_with]=image/&fields=id,title,type,width,height
```
## Filter by Specific Image Type
Get only JPEG images:
```bash
GET /files?filter[type][_eq]=image/jpeg&fields=id,title,type,width,height
```
## Common MIME Types
| Type | MIME |
|------|------|
| JPEG | `image/jpeg` |
| PNG | `image/png` |
| WebP | `image/webp` |
| GIF | `image/gif` |
| SVG | `image/svg+xml` |
| PDF | `application/pdf` |
| JSON | `application/json` |
Use `video/` prefix for videos, `audio/` for audio files, and `application/` for documents.
---
## Document: Sorting
Sort codex items by various fields
URL: /examples/codex/sorting
# Sorting
import { API_BASE_URL } from "../../../constants";
Sort results using the `sort` parameter. Prefix with `-` for descending order.
## Recent Items First
Get the most recently created codex items:
```bash
GET /items/codex?sort=-timestamp_created&limit=10&fields=id,name,timestamp_created
```
## Sort Direction
| Prefix | Direction | Example |
|--------|-----------|---------|
| (none) | Ascending (A-Z, 0-9, oldest first) | `sort=name` |
| `-` | Descending (Z-A, 9-0, newest first) | `sort=-name` |
## Multiple Sort Fields
Sort by multiple fields by separating them with commas:
```bash
GET /items/codex?sort=-timestamp_created,name&limit=10
```
Fields are sorted in the order specified. In the example above, items are first sorted by creation date (newest first), then alphabetically by name for items with the same creation date.
## Sort Alphabetically
Sort items by name in alphabetical order:
```bash
GET /items/codex?sort=name&limit=10&fields=id,name
```
---
## Document: Full-Text Search
Search across all codex fields
URL: /examples/codex/search
# Full-Text Search
import { API_BASE_URL } from "../../../constants";
Use the `search` parameter to perform full-text search across all searchable fields in the codex collection.
```bash
GET /items/codex?search=curator&fields=id,name,description
```
- **Search**: Matches across multiple text fields simultaneously
- **Filter**: Targets specific fields with precise operators
Use search for discovery, filters for precise queries.
## Combine Search with Filters
You can combine full-text search with filters for more refined results:
```bash
GET /items/codex?search=art&filter[id][_gte]=10&fields=id,name,description&limit=10
```
## Search with Sorting
Sort search results by relevance or other fields:
```bash
GET /items/codex?search=collection&sort=-timestamp_created&fields=id,name,description,timestamp_created&limit=10
```
---
## Document: Pagination
Retrieve paginated results with total counts
URL: /examples/codex/pagination
# Pagination
import { API_BASE_URL } from "../../../constants";
Retrieve paginated results using `limit` and `offset` parameters. Include `meta=*` to get total counts for building pagination UI.
```bash
GET /items/codex?limit=5&offset=0&meta=*&fields=id,name
```
## Pagination Parameters
| Parameter | Description | Default |
|-----------|-------------|---------|
| `limit` | Maximum items to return | 100 |
| `offset` | Number of items to skip | 0 |
| `page` | Page number (alternative to offset) | 1 |
| `meta` | Include metadata (`*` for all) | none |
## Meta Response
When `meta=*` is included, the response contains:
```json
{
"data": [...],
"meta": {
"total_count": 1250,
"filter_count": 1250
}
}
```
Total pages = `Math.ceil(total_count / limit)`
For example, with 1250 items and limit=5: `Math.ceil(1250 / 5) = 250 pages`
## Page-Based Pagination
Alternatively, use the `page` parameter instead of `offset`:
```bash
GET /items/codex?limit=10&page=2&meta=*&fields=id,name
```
---
## Document: List Items
Retrieve all codex items with basic fields
URL: /examples/codex/list-items
# List Items
import { API_BASE_URL } from "../../../constants";
Retrieve all codex items with basic fields. Use the `fields` parameter to specify which fields to return and `limit` to control the number of results.
```bash
GET /items/codex?fields=id,name,description&limit=10
```
Always specify the `fields` parameter to return only the data you need. This reduces response size and improves performance.
## Available Fields
Common fields you can request:
| Field | Description |
|-------|-------------|
| `id` | Unique identifier |
| `name` | Item name |
| `description` | Item description |
| `owner` | Ethereum wallet address |
| `ancestor` | Parent item reference |
| `moltbot` | Versioned soul and identity data for AI agents |
| `timestamp_created` | Creation timestamp |
| `timestamp_updated` | Last update timestamp |
---
## Document: Query by Owner
Query all codex items owned by a specific Ethereum wallet address
URL: /examples/codex/items-by-owner
# Query by Owner
import { API_BASE_URL } from "../../../constants";
Query all codex items owned by a specific Ethereum wallet address using Directus filter syntax.
- **Address Format**: The owner address **must be lowercase**. Ethereum addresses are case-insensitive on the blockchain, but for consistent querying in Directus, always use lowercase format.
- **Filter Operator**: Use the `_eq` (equals) operator to match the exact owner address.
- **Filter Syntax**: The filter is passed as a query parameter using the bracket notation.
## Basic Query
Query all codex items owned by address `0x614a61a3b7f2fd8750acaad63b2a0cfe8b8524f1`:
```bash
GET /items/codex?filter[owner][_eq]=0x614a61a3b7f2fd8750acaad63b2a0cfe8b8524f1&fields=id,name,owner&meta=*
```
## Common Mistakes
**1. Using uppercase letters**
```
❌ filter[owner][_eq]=0x614A61A3... (won't match)
✅ filter[owner][_eq]=0x614a61a3... (correct)
```
**2. Missing `0x` prefix**
```
❌ filter[owner][_eq]=614a61a3... (won't match)
✅ filter[owner][_eq]=0x614a61a3... (correct)
```
**3. Wrong operator**
```
❌ filter[owner][_contains]=0x614a... (use _eq for exact match)
✅ filter[owner][_eq]=0x614a61a3... (correct)
```
## Combine with Other Filters
You can combine the owner filter with additional conditions using logical operators:
```bash
GET /items/codex?filter={"_and":[{"owner":{"_eq":"0x614a61a3b7f2fd8750acaad63b2a0cfe8b8524f1"}},{"id":{"_gte":100}}]}
```
This filters for items owned by the address AND with an ID greater than or equal to 100.
---
## Document: Get by ID
Retrieve a specific codex item with all its details
URL: /examples/codex/get-by-id
# Get by ID
import { API_BASE_URL } from "../../../constants";
Retrieve a specific codex item by its unique identifier. Replace `{id}` with the actual item ID.
```bash
GET /items/codex/1
```
## With Specific Fields
You can also limit the returned fields:
```bash
GET /items/codex/1?fields=id,name,description,owner
```
If the item doesn't exist, the API will return a `404` status code with an error message.
---
## Document: Filter by Name
Search for codex items containing a specific name
URL: /examples/codex/filter-by-name
# Filter by Name
import { API_BASE_URL } from "../../../constants";
Search for codex items containing a specific text in their name using the `_contains` filter operator.
```bash
GET /items/codex?filter[name][_contains]=Korka&fields=id,name,description
```
## Filter Operators
| Operator | Description | Example |
|----------|-------------|---------|
| `_eq` | Equals | `filter[name][_eq]=Exact Name` |
| `_neq` | Not equals | `filter[name][_neq]=Excluded` |
| `_contains` | Contains substring | `filter[name][_contains]=partial` |
| `_ncontains` | Does not contain | `filter[name][_ncontains]=excluded` |
| `_starts_with` | Starts with | `filter[name][_starts_with]=prefix` |
| `_ends_with` | Ends with | `filter[name][_ends_with]=suffix` |
String filters are case-sensitive by default. Use `_icontains` for case-insensitive contains matching.
## Exact Match
For an exact name match, use the `_eq` operator:
```bash
GET /items/codex?filter[name][_eq]=My Exact Item Name
```