> ## Documentation Index
> Fetch the complete documentation index at: https://docs.memsync.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Understanding MemSync authentication methods and security

# Authentication

MemSync uses simple API key authentication to protect user data and ensure only authorized access to memories and profiles.

> **Coming Soon**: OAuth 2.0 authentication will be available for enhanced security and easier integration with third-party applications.

## API Key Authentication

### How it Works

MemSync uses API keys for authentication:

<Steps>
  <Step title="API Key Generation">
    Generate an API key from your MemSync dashboard
  </Step>

  <Step title="API Requests">
    Include the API key in the X-API-Key header for all API requests
  </Step>

  <Step title="Key Validation">
    MemSync validates the API key and permissions
  </Step>
</Steps>

### Using API Keys

```python theme={null}
import requests

# Include API key in all API requests
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Example API call
response = requests.post("https://api.memchat.io/v1/memories/search",
    headers=headers,
    json={"query": "user interests", "limit": 5}
)
```

### Key Requirements

* **Header**: X-API-Key
* **Validation**: Must be a valid, active API key
* **Format**: Simple string key

### API Key Features

<CardGroup cols={2}>
  <Card title="Simple Integration" icon="plug">
    Easy integration for third-party applications and services
  </Card>

  <Card title="Enhanced Security" icon="shield">
    App-specific keys with granular permissions and rate limiting
  </Card>

  <Card title="Usage Tracking" icon="chart-bar">
    Monitor API usage and performance
  </Card>

  <Card title="Easy Management" icon="settings">
    Create and manage keys through the dashboard
  </Card>
</CardGroup>

## Security Best Practices

### API Key Security

<AccordionGroup>
  <Accordion title="Secure Storage">
    Store API keys securely and never expose them in client-side code

    ```python theme={null}
    # ✅ Good: Store in environment variables
    import os
    API_KEY = os.environ.get("MEMSYNC_API_KEY")

    # ❌ Bad: Hardcode in source code
    API_KEY = "your_api_key_here"  # Never do this!
    ```
  </Accordion>

  <Accordion title="Key Management">
    Keep your API keys secure and rotate them when needed

    ```python theme={null}
    def make_authenticated_request(endpoint, data):
        headers = {"X-API-Key": API_KEY}
        
        try:
            response = requests.post(endpoint, headers=headers, json=data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 401:
                # Handle invalid API key
                raise AuthenticationError("Invalid API key")
            raise
    ```
  </Accordion>

  <Accordion title="Error Handling">
    Handle authentication errors gracefully

    ```python theme={null}
    def make_authenticated_request(endpoint, data):
        headers = {"X-API-Key": API_KEY}
        
        try:
            response = requests.post(endpoint, headers=headers, json=data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 401:
                # Handle invalid API key
                raise AuthenticationError("Invalid API key")
            raise
    ```
  </Accordion>
</AccordionGroup>

### Network Security

* **HTTPS Only**: All API communications use HTTPS encryption
* **Rate Limiting**: Built-in rate limiting prevents abuse
* **Request Validation**: All requests are validated for proper format and permissions

## User Context

MemSync automatically associates API requests with your account:

```python theme={null}
# The API key is associated with your account
# MemSync automatically handles:
# - User identification
# - Data isolation
# - Access permissions

response = requests.post("https://api.memchat.io/v1/memories",
    headers={"X-API-Key": "YOUR_API_KEY"},
    json={
        "messages": [...],
        "agent_id": "my-chatbot",
        "thread_id": "conversation-123",
        "source": "chat"
    }
)
```

## Error Responses

### Authentication Errors

```json theme={null}
{
  "detail": "Invalid authentication credentials",
  "status_code": 401
}
```

### Common Error Scenarios

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    **Causes:**

    * Missing X-API-Key header
    * Invalid API key
    * API key not found in system

    **Response:**

    ```json theme={null}
    {
      "detail": "Invalid authentication credentials",
      "status_code": 401
    }
    ```
  </Accordion>

  <Accordion title="403 Forbidden">
    **Causes:**

    * Valid API key but insufficient permissions
    * Rate limit exceeded

    **Response:**

    ```json theme={null}
    {
      "detail": "Insufficient permissions",
      "status_code": 403
    }
    ```
  </Accordion>

  <Accordion title="429 Too Many Requests">
    **Causes:**

    * Rate limit exceeded
    * Too many requests in short time period

    **Response:**

    ```json theme={null}
    {
      "detail": "Rate limit exceeded",
      "status_code": 429,
      "retry_after": 60
    }
    ```
  </Accordion>
</AccordionGroup>

## Integration Examples

### Python SDK Example

```python theme={null}
class MemSyncClient:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.memchat.io/v1"
        self.headers = {
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        }
    
    def search_memories(self, query, limit=10):
        response = requests.post(
            f"{self.base_url}/memories/search",
            headers=self.headers,
            json={"query": query, "limit": limit}
        )
        response.raise_for_status()
        return response.json()

# Usage
client = MemSyncClient(api_key="your_api_key")
memories = client.search_memories("user interests")
```

### JavaScript Example

```javascript theme={null}
class MemSyncClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.memchat.io/v1';
    this.headers = {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    };
  }

  async searchMemories(query, limit = 10) {
    const response = await fetch(`${this.baseUrl}/memories/search`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({ query, limit })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response.json();
  }
}

// Usage
const client = new MemSyncClient('your_api_key');
const memories = await client.searchMemories('user interests');
```

## Testing Authentication

### Validate Your API Key

```python theme={null}
def test_authentication(api_key):
    """Test if your API key is valid"""
    headers = {"X-API-Key": api_key}
    
    response = requests.get("https://api.memchat.io/healthcheck", headers=headers)
    
    if response.status_code == 200:
        print("✅ Authentication successful")
        return True
    else:
        print(f"❌ Authentication failed: {response.status_code}")
        print(response.json())
        return False

# Test your API key
test_authentication("your_api_key_here")
```

### Debug Authentication Issues

```python theme={null}
def debug_auth_issues(api_key):
    """Debug common authentication problems"""
    
    # Check if API key is provided
    if not api_key:
        print("❌ API key is missing")
        return
    
    # Check API key format (should be a simple string)
    if len(api_key) < 10:
        print("❌ API key seems too short")
    else:
        print("✅ API key format looks reasonable")
    
    # Test the API key
    try:
        headers = {"X-API-Key": api_key}
        response = requests.get("https://api.memchat.io/healthcheck", headers=headers)
        
        if response.status_code == 200:
            print("✅ API key is valid")
        else:
            print(f"❌ API key validation failed: {response.status_code}")
            print(response.json())
            
    except Exception as e:
        print(f"❌ Error testing API key: {e}")
```

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore the complete API documentation with authentication examples
  </Card>

  <Card title="Quickstart" icon="rocket" href="/quickstart">
    Get started with your first authenticated API calls
  </Card>

  <Card title="Integrations" icon="plug" href="/essentials/integrations">
    Learn about authentication for external integrations
  </Card>

  <Card title="Development" icon="gear" href="/development">
    Set up authentication for local development
  </Card>
</CardGroup>
