> ## 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.

# API Reference

> Complete reference for the MemSync REST API

# MemSync API Reference

The MemSync REST API provides programmatic access to memory management, user profiles, and integrations. This comprehensive reference covers all endpoints, request/response formats, and implementation examples.

## Base URL

All API requests should be made to:

```
https://api.memchat.io/v1
```

## Authentication

MemSync uses API key-based authentication. Include your API key in the X-API-Key header for all requests:

```bash theme={null}
X-API-Key: YOUR_API_KEY
```

<Note>
  API keys are required for all requests. Keep your API key secure and do not share it publicly.
</Note>

## Quick Start

Here's how to make your first API call:

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "X-API-Key": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  # Store a conversation
  response = requests.post("https://api.memchat.io/v1/memories",
      headers=headers,
      json={
          "messages": [
              {"role": "user", "content": "I'm a software engineer who loves hiking"},
              {"role": "assistant", "content": "That's a great combination of technical and outdoor interests!"}
          ],
          "agent_id": "my-chatbot",
          "thread_id": "conversation-123",
          "source": "chat"
      }
  )

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.memchat.io/v1/memories', {
    method: 'POST',
    headers: {
      'X-API-Key': 'YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      messages: [
        {role: 'user', content: "I'\''m a software engineer who loves hiking"},
        {role: 'assistant', content: "That'\''s a great combination of technical and outdoor interests!"}
      ],
      agent_id: 'my-chatbot',
      thread_id: 'conversation-123',
      source: 'chat'
    })
  });

  const result = await response.json();
  console.log(result);
  ```

  ```bash cURL theme={null}
  curl -X POST "https://api.memchat.io/v1/memories" \
    -H "X-API-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "messages": [
        {"role": "user", "content": "I'\''m a software engineer who loves hiking"},
        {"role": "assistant", "content": "That'\''s a great combination of technical and outdoor interests!"}
      ],
      "agent_id": "my-chatbot",
      "thread_id": "conversation-123",
      "source": "chat"
    }'
  ```
</CodeGroup>

## API Endpoints Overview

### Memory Management

<CardGroup cols={2}>
  <Card title="Store Memories" icon="plus" href="/api-reference/endpoint/store-memories">
    Extract and store memories from conversations
  </Card>

  <Card title="Search Memories" icon="magnifying-glass" href="/api-reference/endpoint/search-memories">
    Find and retrieve memories using natural language queries
  </Card>

  <Card title="Get Memories" icon="list" href="/api-reference/endpoint/get-memories">
    Retrieve paginated list of user memories
  </Card>

  <Card title="Update Memory" icon="edit" href="/api-reference/endpoint/update-memory">
    Modify existing memory content
  </Card>
</CardGroup>

### User Profiles

<CardGroup cols={2}>
  <Card title="Get Profile" icon="user" href="/api-reference/endpoint/get-profile">
    Retrieve complete user profile with bio and insights
  </Card>

  <Card title="Get Bio" icon="id-card" href="/api-reference/endpoint/get-bio">
    Get user's auto-generated biographical summary
  </Card>

  <Card title="Update Bio" icon="pen" href="/api-reference/endpoint/update-bio">
    Update user's biographical information
  </Card>
</CardGroup>

### Integrations

<CardGroup cols={2}>
  <Card title="Social Integration" icon="share-nodes" href="/api-reference/endpoint/social-integration">
    Import data from social media platforms
  </Card>

  <Card title="File Integration" icon="file" href="/api-reference/endpoint/file-integration">
    Process documents and extract information
  </Card>

  <Card title="Chat Integration" icon="comments" href="/api-reference/endpoint/chat-integration">
    Import conversation history from chat platforms
  </Card>

  <Card title="Integration Status" icon="clock" href="/api-reference/endpoint/integration-status">
    Check the status of processing tasks
  </Card>
</CardGroup>

### API Key Management

<CardGroup cols={2}>
  <Card title="Create API Key" icon="key" href="/api-reference/endpoint/create-api-key">
    Generate new API keys for third-party apps
  </Card>

  <Card title="List API Keys" icon="list" href="/api-reference/endpoint/list-api-keys">
    View all API keys for the authenticated user
  </Card>

  <Card title="Delete API Key" icon="trash" href="/api-reference/endpoint/delete-api-key">
    Revoke and delete existing API keys
  </Card>
</CardGroup>

## Standard Response Format

All API responses follow a consistent format:

### Success Response

```json theme={null}
{
  "data": {
    // Response data specific to the endpoint
  },
  "status": "success",
  "timestamp": "2024-03-20T10:00:00Z"
}
```

### Error Response

```json theme={null}
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request format",
    "details": {
      "field": "messages",
      "reason": "At least one message is required"
    }
  },
  "status": "error",
  "timestamp": "2024-03-20T10:00:00Z"
}
```

## HTTP Status Codes

| Status Code | Description                                                  |
| ----------- | ------------------------------------------------------------ |
| `200`       | Success - Request completed successfully                     |
| `201`       | Created - Resource created successfully                      |
| `400`       | Bad Request - Invalid request format or parameters           |
| `401`       | Unauthorized - Invalid or missing authentication             |
| `403`       | Forbidden - Insufficient permissions                         |
| `404`       | Not Found - Resource does not exist                          |
| `422`       | Unprocessable Entity - Valid request but cannot be processed |
| `429`       | Too Many Requests - Rate limit exceeded                      |
| `500`       | Internal Server Error - Server error occurred                |

## Rate Limiting

The MemSync API implements rate limiting to ensure service quality:

* **Standard Rate Limit**: 100 requests per minute per user
* **Integration Endpoints**: 10 requests per minute per user
* **Search Endpoints**: 50 requests per minute per user

### Rate Limit Headers

```bash theme={null}
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
```

### Handling Rate Limits

```python theme={null}
import time
import requests

def make_request_with_retry(url, headers, data, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(url, headers=headers, json=data)
        
        if response.status_code == 429:
            # Rate limited, wait and retry
            retry_after = int(response.headers.get('Retry-After', 60))
            time.sleep(retry_after)
            continue
        
        return response
    
    raise Exception("Max retries exceeded")
```

## Error Handling

### Common Error Codes

<AccordionGroup>
  <Accordion title="AUTHENTICATION_ERROR">
    Invalid or missing authentication credentials

    ```json theme={null}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "Invalid API key",
        "details": {
          "reason": "Token has expired"
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="VALIDATION_ERROR">
    Request validation failed

    ```json theme={null}
    {
      "error": {
        "code": "VALIDATION_ERROR", 
        "message": "Invalid request format",
        "details": {
          "field": "limit",
          "reason": "Must be between 1 and 100"
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="RESOURCE_NOT_FOUND">
    Requested resource does not exist

    ```json theme={null}
    {
      "error": {
        "code": "RESOURCE_NOT_FOUND",
        "message": "Memory not found",
        "details": {
          "memory_id": "mem_123",
          "reason": "Memory does not exist or user lacks access"
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="RATE_LIMIT_EXCEEDED">
    Too many requests in a given time period

    ```json theme={null}
    {
      "error": {
        "code": "RATE_LIMIT_EXCEEDED",
        "message": "Rate limit exceeded",
        "details": {
          "limit": 100,
          "reset_time": "2024-03-20T10:01:00Z"
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Pagination

Many endpoints support pagination for large datasets:

### Request Parameters

```json theme={null}
{
  "page": 1,
  "page_size": 20
}
```

### Response Format

```json theme={null}
{
  "data": [...],
  "pagination": {
    "page": 1,
    "page_size": 20,
    "total_items": 150,
    "total_pages": 8,
    "has_next": true,
    "has_previous": false
  }
}
```

### Example Implementation

```python theme={null}
def get_all_memories(headers):
    all_memories = []
    page = 1
    
    while True:
        response = requests.get(f"https://api.memchat.io/v1/memories",
            headers=headers,
            params={"page": page, "page_size": 50}
        )
        
        data = response.json()
        all_memories.extend(data['data'])
        
        if not data['pagination']['has_next']:
            break
            
        page += 1
    
    return all_memories
```

## SDKs and Libraries

### Official SDKs

<CardGroup cols={2}>
  <Card title="Python SDK" icon="python">
    Coming soon - Official Python SDK with full API coverage
  </Card>

  <Card title="JavaScript SDK" icon="javascript">
    Coming soon - Official JavaScript/TypeScript SDK
  </Card>

  <Card title="Go SDK" icon="golang">
    Planned - Go SDK for server-side applications
  </Card>

  <Card title="PHP SDK" icon="php">
    Planned - PHP SDK for web applications
  </Card>
</CardGroup>

### Community Libraries

We encourage community contributions! If you've built a library for MemSync, let us know and we'll feature it here.

## Webhooks (Coming Soon)

Webhooks will allow your application to receive real-time notifications about:

* Memory processing completion
* Integration task updates
* Profile changes
* System events

```json theme={null}
{
  "event": "memory.created",
  "data": {
    "memory_id": "mem_123",
    "user_id": "user_456",
    "categories": ["career", "interests"]
  },
  "timestamp": "2024-03-20T10:00:00Z"
}
```

## OpenAPI Specification

Download the complete OpenAPI specification for the MemSync API:

<Card title="OpenAPI Spec" icon="download" href="/api-reference/openapi.json">
  Download the OpenAPI 3.0 specification file for code generation and testing
</Card>

## Support and Feedback

### Getting Help

* **Documentation**: Comprehensive guides and examples
* **Community**: Join our Discord for community support
* **GitHub Issues**: Report bugs and request features
* **Email Support**: Contact us at [api@memsync.ai](mailto:api@memsync.ai)

### Status Page

Monitor API status and performance:

<Card title="API Status" icon="activity" href="https://status.memsync.ai">
  Check real-time API status, uptime, and incident reports
</Card>

## Next Steps

Ready to start building with MemSync? Here are some great places to begin:

<CardGroup cols={2}>
  <Card title="Quickstart Guide" icon="rocket" href="/quickstart">
    Get up and running with your first API calls in minutes
  </Card>

  <Card title="Memory Management" icon="brain" href="/api-reference/endpoint/store-memories">
    Learn how to store and retrieve user memories
  </Card>

  <Card title="User Profiles" icon="user" href="/api-reference/endpoint/get-profile">
    Explore auto-generated user profiles and insights
  </Card>

  <Card title="Integrations" icon="plug" href="/api-reference/endpoint/social-integration">
    Import data from external sources to enrich profiles
  </Card>
</CardGroup>
