Skip to main content
doc0blade47/mem0documentation home
Sign in

Server API Endpoints

Last updated Oct 11, 2026100% grounded
Relevant source files

The following files were used as context for generating this wiki page:

Overview

The self-hosted server provides a FastAPI application bootstrap layer that initializes application state, registers routers, enforces rate limits, handles CORS, and maps validation errors. This HTTP interface powers remote memory synchronization, project scoping, and administrative management across client SDKs and dashboard integrations.

Sources: server/main.py:178-342, FastAPI Application

REST API Architecture and Routing

Endpoint Inventory and Path Conventions

The FastAPI server exposes modular REST endpoints grouped into distinct API submodules, each mounted under dedicated path prefixes. These route definitions integrate with Pydantic schemas and database models to handle authentication, manage programmatic keys, inspect aggregated entities, and record audit requests.

The route endpoints map across core functional domains including authentication (/auth), memory management (/memories), system configuration (/configure), API key administration (/api-keys), request log telemetry (/requests), and entity browsing (/entities). Client integrations and dashboard interfaces reference these exact paths via centralized utility configurations and typed API client definitions.

SubmodulePath PrefixKey MethodsDescription
Auth/authGET, POSTSetup status, registration, login, token refresh, profile inspection, password change, and onboarding completion
Memories/memoriesGET, POST, DELETE, PUTMemory CRUD operations, history inspection, reset triggers, and generation instructions
Configure/configureGET, POSTSystem configuration and provider settings
API Keys/api-keysGET, POST, DELETEActive key enumeration, creation of new API keys with secret generation, and key revocation
Requests/requestsGETRequest log telemetry and audit querying
Entities/entitiesGET, DELETEAggregated entity listing across user, agent, and run scopes, and cascading memory deletions

Sources: server/routers/entities.py:12-16, server/routers/api_keys.py:14, server/dashboard/src/utils/api-endpoints.ts:1-34

Pydantic Schemas and Data Models

Request validation and response serialization rely on explicit Pydantic models across all routers. Submodules enforce specific payload contracts for entity grouping, API key lifecycle management, and telemetry logging.

class Entity(BaseModel):
    id: str
    type: EntityType
    total_memories: int
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
 

Sources: server/routers/entities.py:20-26

class CreateKeyRequest(BaseModel):
    label: str
 
 
class CreateKeyResponse(BaseModel):
    id: str
    key: str
    label: str
    key_prefix: str
    created_at: datetime
 
 
class KeyListItem(BaseModel):
    id: str
    label: str
    key_prefix: str
    created_at: datetime
    last_used_at: datetime | None
 

Sources: server/routers/api_keys.py:17-35

export interface ApiRequestLog {
  id: string;
  created_at: string;
  method: string;
  path: string;
  status_code: number;
  latency_ms: number;
  auth_type: string;
}
 
export type EntityType = "user" | "agent" | "run";
 
export interface Entity {
  id: string;
  type: EntityType;
  total_memories: number;
  created_at: string | null;
  updated_at: string | null;
}

Sources: server/dashboard/src/types/api.ts:26-44

Memory Operations and Data Schemas

Endpoint Routing and Payload Structures

Memory management endpoints provide full CRUD capabilities alongside specialized sub-routes for inspecting history, configuring providers, resetting data stores, and generating system instructions. The base path for memory operations is defined at /memories, with dynamic sub-routes supporting resource identification via unique memory identifiers and entity categorization.

export const MEMORY_ENDPOINTS = {
  BASE: "/memories",
  BY_ID: (memoryId: string) => `/memories/${memoryId}`,
  HISTORY: (memoryId: string) => `/memories/${memoryId}/history`,
  CONFIGURE: "/configure",
  CONFIGURE_PROVIDERS: "/configure/providers",
  RESET: "/reset",
  GENERATE_INSTRUCTIONS: "/generate-instructions",
} as const;

Sources: server/dashboard/src/utils/api-endpoints.ts:11-19

The Memory data structure standardizes serialization for both single-item retrievals and collection responses. Each memory object exposes an unique identifier, the memory text payload, optional scoping metadata for user or agent associations, and timestamps tracking creation and modification events.

export interface Memory {
  id: string;
  memory: string;
  user_id?: string;
  agent_id?: string;
  created_at?: string;
  updated_at?: string;
}

Sources: server/dashboard/src/types/api.ts:1-8

Endpoint PathParameter / PayloadDescription
/memoriesPOST / GETCreate a new memory record or list stored memories across scoped contexts
/memories/{memoryId}GET / PUT / DELETERetrieve, update, or delete a specific memory entry by its unique identifier
/memories/{memoryId}/historyGETFetch the complete modification history log for a designated memory record
/configureGET / POSTInspect or update global system configuration settings
/configure/providersGET / POSTManage external LLM and vector store provider integrations
/resetPOSTPurge system storage and reset persistent memory stores
/generate-instructionsPOSTAutomatically synthesize agent instruction sets from recorded memory contexts

Sources: server/dashboard/src/utils/api-endpoints.ts:11-19, server/dashboard/src/types/api.ts:1-8

Note

Scoping identifiers such as user_id and agent_id are optional on the base Memory interface, allowing global memory creation when neither parameter is provided during ingestion. Sources: server/dashboard/src/types/api.ts:1-8

Entity Browsing and Management

Entity Routing and Schemas

The entity routing module exposes endpoints prefixed at /entities under the entities router tag to inspect, aggregate, and purge vector store payloads by their scoping fields. Authentication is enforced via dependency injection, requiring standard verification for listing operations and administrative privileges for deletion requests.

router = APIRouter(prefix="/entities", tags=["entities"])
 
SCAN_LIMIT = 10_000
 
EntityType = Literal["user", "agent", "run"]
TYPE_TO_FIELD: dict[EntityType, str] = {"user": "user_id", "agent": "agent_id", "run": "run_id"}
 

Sources: server/routers/entities.py:12-18

Entity categories are defined by the EntityType literal union supporting "user", "agent", and "run" scopes. The TYPE_TO_FIELD dictionary maps each entity type to its corresponding payload metadata key: "user" maps to "user_id", "agent" maps to "agent_id", and "run" maps to "run_id".

export type EntityType = "user" | "agent" | "run";
 
export interface Entity {
  id: string;
  type: EntityType;
  total_memories: number;
  created_at: string | null;
  updated_at: string | null;
}

Sources: server/dashboard/src/types/api.ts:36-44

The Pydantic Entity model and its TypeScript dashboard equivalent structure the serialized representation returned to clients. Each entity record contains a unique string identifier, its category type, the total memory count aggregated across matching payloads, and ISO-8601 timestamps marking creation and update events.

class Entity(BaseModel):
    id: str
    type: EntityType
    total_memories: int
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
 

Sources: server/routers/entities.py:20-26

Endpoint PathMethodAuth DependencyDescription
/entitiesGETverify_authScan vector store payloads and return aggregated entity summaries
/entities/{entity_type}/{entity_id}DELETErequire_adminPurge all memories linked to the specified entity type and identifier

Sources: server/routers/entities.py:43-44, server/routers/entities.py:70-71, server/dashboard/src/utils/api-endpoints.ts:30-33

Note

The list_entities endpoint scans vector store payloads up to a hardcoded SCAN_LIMIT of 10,000 records, building dynamic aggregation buckets across user, agent, and run identifier fields. Sources: server/routers/entities.py:14-15, server/routers/entities.py:45-47

Aggregation and Deletion Logic

def _iter_payloads() -> list[dict[str, Any]]:
    results = get_memory_instance().vector_store.list(top_k=SCAN_LIMIT)
    rows = results[0] if results and isinstance(results, list) and isinstance(results[0], list) else results or []
    return [getattr(row, "payload", None) or {} for row in rows]
 

Sources: server/routers/entities.py:28-32

for payload in _iter_payloads():
    created = _parse_timestamp(payload.get("created_at"))
    updated = _parse_timestamp(payload.get("updated_at")) or created
 
    for entity_type, field in TYPE_TO_FIELD.items():
        value = payload.get(field)
        if not value:
            continue
        bucket = buckets[(entity_type, str(value))]
        bucket["total_memories"] += 1
        if created and (bucket["created_at"] is None or created < bucket["created_at"]):
            bucket["created_at"] = created
        if updated and (bucket["updated_at"] is None or updated > bucket["updated_at"]):
            bucket["updated_at"] = updated
 
return [
    Entity(id=entity_id, type=entity_type, **data)
    for (entity_type, entity_id), data in sorted(buckets.items(), key=lambda item: (item[0][0], item[0][1]))
]

Sources: server/routers/entities.py:49-67

@router.delete("/{entity_type}/{entity_id}", response_model=MessageResponse)
def delete_entity(entity_type: EntityType, entity_id: str, _auth=Depends(require_admin)):
    try:
        get_memory_instance().delete_all(**{TYPE_TO_FIELD[entity_type]: entity_id})
    except Exception:
        raise upstream_error()
    return MessageResponse(message="Entity deleted")

Sources: server/routers/entities.py:70-76

Warning

Deleting an entity via delete_entity invokes get_memory_instance().delete_all(...) filtered by the mapped field name, permanently removing every memory associated with that identifier across the underlying data store. Sources: server/routers/entities.py:70-73

API Key Lifecycle and Rotation

Key Management Endpoints and Schemas

The API key router manages administrative credential generation, prefix enumeration, and revocation under the /api-keys route prefix with the api-keys tag. All operations require authenticated user sessions via dependency injection.

router = APIRouter(prefix="/api-keys", tags=["api-keys"])
 
 
class CreateKeyRequest(BaseModel):
    label: str
 
 
class CreateKeyResponse(BaseModel):
    id: str
    key: str
    label: str
    key_prefix: str
    created_at: datetime
 
 
class KeyListItem(BaseModel):
    id: str
    label: str
    key_prefix: str
    created_at: datetime
    last_used_at: datetime | None
 
    model_config = {"from_attributes": True}
 

Sources: server/routers/api_keys.py:14-37

Endpoint PathMethodStatus CodeDescription
/api-keysGET200List all active API keys created by the authenticated user
/api-keysPOST201Generate and persist a new API key with a given label
/api-keys/{key_id}DELETE200Revoke an existing API key by marking its revocation timestamp

Sources: server/routers/api_keys.py:39-40, server/routers/api_keys.py:62-63, server/routers/api_keys.py:79-80

Note

The list_keys endpoint filters out revoked API keys where revoked_at is not null, ordering active credentials by creation date in descending order. Sources: server/routers/api_keys.py:41-49

Key Generation and Revocation Logic

@router.post("", response_model=CreateKeyResponse, status_code=201)
def create_key(body: CreateKeyRequest, user: User = Depends(require_auth), db: Session = Depends(get_db)):
    full_key, prefix, key_hash = generate_api_key()
    api_key = APIKey(key_prefix=prefix, key_hash=key_hash, label=body.label, created_by=user.id)
    db.add(api_key)
    db.commit()
    db.refresh(api_key)
 
    return CreateKeyResponse(
        id=str(api_key.id),
        key=full_key,
        label=api_key.label,
        key_prefix=prefix,
        created_at=api_key.created_at,
    )

Sources: server/routers/api_keys.py:62-76

@router.delete("/{key_id}", response_model=MessageResponse)
def revoke_key(key_id: str, user: User = Depends(require_auth), db: Session = Depends(get_db)):
    try:
        key_uuid = uuid.UUID(key_id)
    except (TypeError, ValueError):
        raise HTTPException(status_code=404, detail="API key not found.")
    api_key = db.get(APIKey, key_uuid)
    if api_key is None or api_key.created_by != user.id:
        raise HTTPException(status_code=404, detail="API key not found.")
    if api_key.revoked_at is not None:
        raise HTTPException(status_code=400, detail="API key is already revoked.")
 
    api_key.revoked_at = datetime.now(timezone.utc)
    db.commit()
    return MessageResponse(message="API key revoked.")

Sources: server/routers/api_keys.py:79-93

Warning

The revoke_key endpoint validates that the target identifier parses as a valid UUID and that the key belongs to the requesting user before setting revoked_at to the current UTC time. Attempting to revoke an already revoked key raises a 400 status error. Sources: server/routers/api_keys.py:81-91

Telemetry and Request Logging Endpoints

Request Log Aggregation and Schemas

Request logging endpoints capture runtime telemetry across server operations. The dashboard client references these endpoints through the REQUEST_ENDPOINTS utility mapping.

export const REQUEST_ENDPOINTS = {
  BASE: "/requests",
} as const;

Sources: server/dashboard/src/utils/api-endpoints.ts:26-28

Telemetry data structures are represented in the frontend via the ApiRequestLog interface, capturing audit metadata including execution path, HTTP method, response status, processing latency, and authentication scheme.

export interface ApiRequestLog {
  id: string;
  created_at: string;
  method: string;
  path: string;
  status_code: number;
  latency_ms: number;
  auth_type: string;
}

Sources: server/dashboard/src/types/api.ts:26-34

Field NameTypeDescription
idstringUnique identifier for the recorded request log entry
created_atstringTimestamp indicating when the request was processed
methodstringHTTP request method (e.g. GET, POST, DELETE)
pathstringRequest path or route target
status_codenumberHTTP response status code returned by the server
latency_msnumberProcessing duration measured in milliseconds
auth_typestringAuthentication mechanism utilized for the request

Sources: server/dashboard/src/types/api.ts:27-33

Note

Request logs aggregate transactional metrics across all incoming API calls, enabling administrative audit trails and performance monitoring within the dashboard views. Sources: server/dashboard/src/types/api.ts:26-34

Health Inspection and System Status

Setup Status and Health Probes

The server provides endpoints to inspect application readiness, configuration state, and setup initialization requirements. The dashboard client accesses setup verification via authentication endpoint paths mapped in the utility configuration.

export const AUTH_ENDPOINTS = {
  SETUP_STATUS: "/auth/setup-status",
  REGISTER: "/auth/register",
  LOGIN: "/auth/login",
  REFRESH: "/auth/refresh",
  ME: "/auth/me",
  CHANGE_PASSWORD: "/auth/change-password",
  ONBOARDING_COMPLETE: "/auth/onboarding-complete",
} as const;

Sources: server/dashboard/src/utils/api-endpoints.ts:1-9

Endpoint ConstantPath ValueDescription
SETUP_STATUS/auth/setup-statusInspects whether the server requires initial admin user registration
REGISTER/auth/registerRegisters the initial administrator account during setup
LOGIN/auth/loginAuthenticates existing users and issues access credentials
REFRESH/auth/refreshRefreshes authentication tokens
ME/auth/meRetrieves profile details for the currently authenticated user
CHANGE_PASSWORD/auth/change-passwordUpdates user credentials
ONBOARDING_COMPLETE/auth/onboarding-completeMarks initial onboarding flows as complete

Sources: server/dashboard/src/utils/api-endpoints.ts:2-8

Note

The /auth/setup-status endpoint allows unauthenticated clients to determine whether the server has completed its initial administrator provisioning, guiding the frontend Dashboard Architecture setup wizard. Sources: server/dashboard/src/utils/api-endpoints.ts:2

Was this page helpful?