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

# Setup

The MoonKey REST API provides programmatic access to all authentication and wallet management functionality. Use the API to manage users, create wallets, handle authentication flows, and more from your backend.

## Prerequisites

Before you begin, make sure you have:

* [Created a MoonKey app](/get-started/dashboard/create-new-app) in the dashboard
* Obtained your API keys from the dashboard

## Base URL

All requests to the MoonKey API must be made to the following base URL:

```
https://api.moonkey.fun
```

**HTTPS is required for all requests.** HTTP requests will be rejected.

## Authentication

The MoonKey API uses **Bearer token authentication**. You must include your API key in the `Authorization` header of every request.

### API Keys

MoonKey provides two types of API keys:

| Key Type      | Format        | Usage                   | Security                                 |
| ------------- | ------------- | ----------------------- | ---------------------------------------- |
| **Test Keys** | `sk_test_...` | Development and testing | Safe to use in test environments         |
| **Live Keys** | `sk_live_...` | Production              | Keep secure, never expose in client code |

<Warning>
  Never share your secret API keys in publicly accessible areas such as GitHub, client-side code, or browser developer tools. Always use environment variables to store your keys.
</Warning>

### Authentication Header

Include your API key in the `Authorization` header using the Bearer scheme:

```
Authorization: Bearer {your_api_key}
```

### Required Headers

Every API request must include these headers:

<ParamField header="Authorization" type="string" required>
  Bearer token with your MoonKey API key (test or live).

  Example: `Bearer sk_test_pRqweh3wvWmJAAVYv7Z0T5iPLzFM4ql0muoyQcjOxGeN3p1r`
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Set to `application/json` for all requests with a body.
</ParamField>

## Getting Your API Keys

Retrieve your API keys from the MoonKey Dashboard:

1. Log in to your [MoonKey Dashboard](https://dashboard.moonkey.fun)
2. Select your app from the dropdown
3. Navigate to **API Keys** in the sidebar
4. Copy your test or live API key
5. Store it securely in your environment variables

<Tip>
  Start with test keys during development. Switch to live keys only when you're ready to go to production.
</Tip>

## Example Requests

Here are examples of making authenticated requests to the MoonKey API in different languages:

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X GET "https://api.moonkey.fun/v1/auth/users/user_123" \
      -H "Authorization: Bearer sk_test_your_api_key_here" \
      -H "Content-Type: application/json"
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const apiKey = process.env.MOONKEY_SECRET_KEY;

    const response = await fetch('https://api.moonkey.fun/v1/auth/users/user_123', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      }
    });

    const data = await response.json();
    console.log(data);
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    const axios = require('axios');

    const apiKey = process.env.MOONKEY_SECRET_KEY;

    const response = await axios.get(
      'https://api.moonkey.fun/v1/auth/users/user_123',
      {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log(response.data);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import os

    api_key = os.environ.get('MOONKEY_SECRET_KEY')

    url = "https://api.moonkey.fun/v1/auth/users/user_123"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    response = requests.get(url, headers=headers)
    data = response.json()
    print(data)
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    package main

    import (
        "fmt"
        "io"
        "net/http"
        "os"
    )

    func main() {
        apiKey := os.Getenv("MOONKEY_SECRET_KEY")
        
        client := &http.Client{}
        req, _ := http.NewRequest("GET", "https://api.moonkey.fun/v1/auth/users/user_123", nil)
        
        req.Header.Add("Authorization", "Bearer "+apiKey)
        req.Header.Add("Content-Type", "application/json")
        
        resp, _ := client.Do(req)
        defer resp.Body.Close()
        
        body, _ := io.ReadAll(resp.Body)
        fmt.Println(string(body))
    }
    ```
  </Tab>
</Tabs>

## Making POST Requests

For requests that create or update resources, include a JSON body:

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST "https://api.moonkey.fun/v1/auth/users" \
      -H "Authorization: Bearer sk_test_your_api_key_here" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "user@example.com"
      }'
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const apiKey = process.env.MOONKEY_SECRET_KEY;

    const response = await fetch('https://api.moonkey.fun/v1/auth/users', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: 'user@example.com'
      })
    });

    const data = await response.json();
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests
    import os

    api_key = os.environ.get('MOONKEY_SECRET_KEY')

    url = "https://api.moonkey.fun/v1/auth/users"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "email": "user@example.com"
    }

    response = requests.post(url, json=payload, headers=headers)
    data = response.json()
    ```
  </Tab>
</Tabs>

## Environment Variables

Store your API keys securely using environment variables:

```bash .env theme={null}
# Never commit this file to version control!
MOONKEY_SECRET_KEY=sk_test_your_api_key_here
```

**Loading environment variables:**

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    // Using dotenv package
    require('dotenv').config();

    const apiKey = process.env.MOONKEY_SECRET_KEY;
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    # Using python-dotenv package
    from dotenv import load_dotenv
    import os

    load_dotenv()
    api_key = os.environ.get('MOONKEY_SECRET_KEY')
    ```
  </Tab>

  <Tab title="Next.js">
    ```javascript theme={null}
    // Next.js automatically loads .env.local files
    // Use NEXT_PUBLIC_ prefix only for client-side variables

    const apiKey = process.env.MOONKEY_SECRET_KEY;
    ```
  </Tab>
</Tabs>

## Response Format

All API responses are returned in JSON format with consistent structure:

### Success Response

```json theme={null}
{
  "id": "user_123",
  "email": "user@example.com",
  "created_at": "2024-01-15T10:30:00Z",
  // ... additional fields
}
```

### Error Response

```json theme={null}
{
  "error": {
    "code": "invalid_request",
    "message": "Missing required field: email"
  }
}
```

## HTTP Status Codes

The MoonKey API uses standard HTTP status codes:

| Status Code | Meaning                                                 |
| ----------- | ------------------------------------------------------- |
| `200`       | Success - Request completed successfully                |
| `201`       | Created - Resource created successfully                 |
| `400`       | Bad Request - Invalid request parameters                |
| `401`       | Unauthorized - Invalid or missing API key               |
| `403`       | Forbidden - API key doesn't have required permissions   |
| `404`       | Not Found - Resource doesn't exist                      |
| `429`       | Too Many Requests - Rate limit exceeded                 |
| `500`       | Internal Server Error - Something went wrong on our end |

## Rate Limiting

The MoonKey API implements rate limiting to ensure service reliability:

* **Test environment**: 100 requests per minute
* **Production environment**: 1000 requests per minute

When you exceed the rate limit, you'll receive a `429` status code. The response includes headers indicating when you can retry:

```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640000000
```

<Tip>
  Implement exponential backoff when you receive rate limit errors to ensure your application handles limits gracefully.
</Tip>

## Best Practices

### Security

* **Never expose API keys in client-side code** - API keys should only be used from your backend
* **Use environment variables** - Store keys in `.env` files and never commit them to version control
* **Rotate keys regularly** - Generate new keys periodically and revoke old ones
* **Use test keys in development** - Keep live keys separate and only use them in production

### Error Handling

Always implement proper error handling:

```javascript theme={null}
try {
  const response = await fetch('https://api.moonkey.fun/v1/auth/users/user_123', {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }

  const data = await response.json();
  return data;
} catch (error) {
  console.error('API request failed:', error.message);
  // Handle error appropriately
}
```

## Testing Your Integration

Test your API integration with these steps:

1. **Use test API keys** - Start with `sk_test_...` keys
2. **Test authentication** - Verify your API key works by fetching user data
3. **Handle errors** - Test error scenarios (invalid keys, missing parameters, etc.)
4. **Check rate limits** - Ensure your application handles rate limiting properly
5. **Validate responses** - Verify response structure matches documentation

## Next Steps

Now that you've set up API authentication, explore the available endpoints:

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Manage user authentication and sessions
  </Card>

  <Card title="Users" icon="users" href="/api-reference/users/get-user">
    Create and manage user accounts
  </Card>

  <Card title="Wallets" icon="wallet" href="/api-reference/managed-wallets/get-wallet">
    Create and manage user wallets
  </Card>

  <Card title="Sessions" icon="clock" href="/api-reference/sessions/verify-session">
    Verify and manage user sessions
  </Card>
</CardGroup>

## Support

Need help with the REST API?

* Check the [API Reference](/api-reference/authentication) for detailed endpoint documentation
* Review [code examples](/get-started/frontend-sdks/react/examples) for common patterns
* Contact support for technical assistance
