# MemoryClient Configuration and Authentication: A Complete Guide to the Mem0 Python SDK

> Master MemoryClient configuration and authentication with the Mem0 Python SDK. Learn to set api key, host, org id, and project id for secure API access.

- Repository: [Mem0/mem0](https://github.com/mem0ai/mem0)
- Tags: how-to-guide
- Published: 2026-03-07

---

**The `MemoryClient` and `AsyncMemoryClient` classes accept `api_key`, `host`, `org_id`, `project_id`, and an optional custom HTTP client, automatically injecting `Authorization` and `Mem0-User-ID` headers and validating credentials via a ping request to the Mem0 API.**

The Mem0 Python SDK provides the primary interface for managing persistent memory through the `MemoryClient` class defined in [`mem0/client/main.py`](https://github.com/mem0ai/mem0/blob/main/mem0/client/main.py). Understanding the available configuration options and authentication flow is essential for securely connecting to either the managed Mem0 cloud service or a self-hosted instance. This guide covers initialization parameters, the authentication mechanism, and practical implementation patterns derived directly from the source code.

## Core Configuration Options for MemoryClient

Both `MemoryClient` (synchronous) and `AsyncMemoryClient` (asynchronous) share identical initialization signatures. The following parameters control how the client connects to the Mem0 API:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `str` | `None` (falls back to `os.getenv("MEM0_API_KEY")`) | The secret token for authenticating requests. **Required**—if unresolved, a `ValueError` is raised. |
| `host` | `str` | `"https://api.mem0.ai"` | Base URL of the Mem0 service. Override this for self-hosted deployments or testing environments. |
| `org_id` | `str` | `None` | Organization identifier. Must be supplied together with `project_id` for organization-level scoping. |
| `project_id` | `str` | `None` | Project identifier within the organization. Must be supplied together with `org_id`. |
| `client` | `httpx.Client` or `httpx.AsyncClient` | `None` | An optional pre-configured HTTPX client. If provided, its `base_url` and headers are overwritten with Mem0-specific values. |

Additionally, the client derives a `user_id` internally by generating an MD5 hash of the API key (as seen in [`mem0/memory/setup.py`](https://github.com/mem0ai/mem0/blob/main/mem0/memory/setup.py)). This value is sent as the `Mem0-User-ID` header with every request.

## How Authentication Works in Mem0

The `MemoryClient` implements a multi-layered authentication strategy that validates credentials at initialization and secures all subsequent requests.

### Header Injection

Upon instantiation, the client prepares two mandatory HTTP headers that are injected into every request:

1.  **`Authorization: Token <API_KEY>`** – The standard bearer token format used by the Mem0 API.
2.  **`Mem0-User-ID: <MD5_HASH>`** – A deterministic identifier derived from the API key to track usage and enforce rate limits.

These headers are configured in the `__init__` method of [`mem0/client/main.py`](https://github.com/mem0ai/mem0/blob/main/mem0/client/main.py) and applied to the underlying HTTP client.

### Ping Validation

During construction, the client immediately calls `_validate_api_key()`, which sends a lightweight `GET` request to `/v1/ping/`. This serves two purposes:

-   **Verification**: Confirms the API key is active and valid.
-   **Metadata Retrieval**: The response payload may contain `org_id`, `project_id`, and `user_email`, which the client stores for later use.

If the ping request fails (e.g., returns a 401 or 403), the client raises a `ValueError` with the server's error message, preventing the creation of an invalid client instance.

### Organization and Project Scoping

When both `org_id` and `project_id` are provided during initialization, the client automatically appends these as query parameters to every API request via the private `_prepare_params` helper method. This enforces organization-level isolation for memory operations.

**Important**: Supplying only one of `org_id` or `project_id` triggers a `ValueError`, as the API requires both identifiers for scoped requests.

## Practical Configuration Examples

### Minimal Setup Using Environment Variables

The simplest configuration relies on the `MEM0_API_KEY` environment variable, eliminating the need to hardcode secrets:

```python
import os
from mem0 import MemoryClient

# Set the API key in the environment

os.environ["MEM0_API_KEY"] = "sk-your-mem0-key"

# Client automatically resolves the key from the environment

client = MemoryClient()
client.add("I love pizza!")

```

### Explicit API Key and Custom Host

For self-hosted deployments or explicit configuration, provide the `api_key` and `host` parameters directly:

```python
from mem0 import MemoryClient

client = MemoryClient(
    api_key="sk-my-personal-key",
    host="https://api.mem0.ai",  # Override for self-hosted: "http://localhost:8000"

)

```

### Organization and Project Scoping

To isolate memory within a specific organization and project, supply both identifiers:

```python
client = MemoryClient(
    api_key="sk-my-key",
    org_id="org_12345",
    project_id="proj_67890",
)

# All subsequent requests include org_id and project_id as query parameters

```

### Using a Pre-Configured HTTPX Client

For advanced networking requirements such as custom timeouts, proxies, or SSL settings, pass a pre-configured `httpx.Client`:

```python
import httpx
from mem0 import MemoryClient

custom_httpx = httpx.Client(
    timeout=120,
    proxies={"https://": "http://my-proxy:3128"}
)

client = MemoryClient(
    api_key="sk-key",
    client=custom_httpx,
)

```

### Asynchronous Configuration

The `AsyncMemoryClient` accepts identical parameters and works with `asyncio`:

```python
import asyncio
from mem0 import AsyncMemoryClient

async def demo():
    async with AsyncMemoryClient(api_key="sk-key") as client:
        await client.add({"role": "user", "content": "Tell me a joke!"})

asyncio.run(demo())

```

## Source Code References

The configuration and authentication logic is implemented across the following files in the `mem0ai/mem0` repository:

- **[`mem0/client/main.py`](https://github.com/mem0ai/mem0/blob/main/mem0/client/main.py)** – Contains the `MemoryClient.__init__` (lines 24-46) and `AsyncMemoryClient.__init__` (lines 60-66) methods, header preparation, and the `_validate_api_key` method (lines 95-115) that performs the ping request.
- **[`mem0/client/main.py`](https://github.com/mem0ai/mem0/blob/main/mem0/client/main.py)** – Also houses the `_prepare_params` helper (lines 27-50) that manages organization and project query parameters.
- **[`mem0/memory/setup.py`](https://github.com/mem0ai/mem0/blob/main/mem0/memory/setup.py)** – Implements the `get_user_id` utility (lines 12-33) that generates the MD5 hash of the API key for the `Mem0-User-ID` header.
- **[`mem0/client/project.py`](https://github.com/mem0ai/mem0/blob/main/mem0/client/project.py)** – Defines the `Project` and `AsyncProject` classes for organization-level operations, accessible via `client.project` when scoped.

## Summary

- **Initialization**: `MemoryClient` and `AsyncMemoryClient` accept `api_key`, `host`, `org_id`, `project_id`, and an optional `httpx.Client` instance.
- **Authentication**: The client automatically injects `Authorization: Token <API_KEY>` and `Mem0-User-ID: <MD5_HASH>` headers into every request.
- **Validation**: A ping request to `/v1/ping/` runs during initialization to verify the API key and retrieve user metadata.
- **Scoping**: Providing both `org_id` and `project_id` appends these as query parameters to all requests; providing only one raises a `ValueError`.
- **Environment Fallback**: If `api_key` is omitted, the client reads from the `MEM0_API_KEY` environment variable.

## Frequently Asked Questions

### What happens if I don't provide an API key when initializing MemoryClient?

If you instantiate `MemoryClient()` without passing an `api_key` argument, the constructor attempts to read the `MEM0_API_KEY` environment variable. If neither the argument nor the environment variable is present, the client raises a `ValueError` immediately, preventing the creation of an unauthenticated instance.

### Can I use MemoryClient with a self-hosted Mem0 instance?

Yes. Pass the `host` parameter during initialization to point to your self-hosted deployment. For example: `MemoryClient(api_key="your-key", host="http://localhost:8000")`. The client will use this base URL for all API requests instead of the default `https://api.mem0.ai`.

### How do org_id and project_id affect API requests?

When both `org_id` and `project_id` are provided, the client automatically appends them as query parameters to every request via the internal `_prepare_params` method. This scopes all memory operations to that specific organization and project. If you provide only one of these parameters without the other, the client raises a `ValueError` because the API requires both identifiers together.

### Is AsyncMemoryClient configured differently than MemoryClient?

No. `AsyncMemoryClient` accepts exactly the same initialization parameters as `MemoryClient`, including `api_key`, `host`, `org_id`, `project_id`, and the optional `client` argument for a pre-configured `httpx.AsyncClient`. The authentication headers, ping validation, and organization scoping logic are identical between both classes.