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

# Avatar API Overview

> Comprehensive API for creating, managing, and publishing AI avatars

## Overview

The Avatar API provides endpoints for generating AI avatars, managing avatar metadata, publishing to the community feed, and retrieving avatar assets. All endpoints require authentication via API key.

## Base URL

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

## Authentication

All requests must include your API key in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Core Endpoints

| Method | Endpoint                      | Description                       |
| ------ | ----------------------------- | --------------------------------- |
| POST   | `/avatars/generate`           | Generate a new avatar from prompt |
| POST   | `/avatars/percify-yourself`   | Create avatar from photo          |
| POST   | `/avatars/cast`               | Generate multi-character scene    |
| GET    | `/avatars/{avatarId}`         | Get avatar details                |
| GET    | `/avatars`                    | List your avatars                 |
| PATCH  | `/avatars/{avatarId}`         | Update avatar metadata            |
| POST   | `/avatars/{avatarId}/publish` | Publish avatar to feed            |
| DELETE | `/avatars/{avatarId}`         | Delete avatar                     |
| POST   | `/avatars/{avatarId}/like`    | Like an avatar                    |
| POST   | `/avatars/{avatarId}/comment` | Comment on avatar                 |
| POST   | `/avatars/{avatarId}/remix`   | Remix/derive from avatar          |

## Avatar Object

```json theme={null}
{
  "id": "avatar_abc123",
  "userId": "user_xyz789",
  "status": "completed",
  "prompt": "cyberpunk warrior, neon lights, futuristic city",
  "negativePrompt": "blurry, low quality",
  "model": "imagen3",
  "imageUrl": "https://cdn.percify.io/avatars/avatar_abc123.png",
  "thumbnailUrl": "https://cdn.percify.io/avatars/avatar_abc123_thumb.png",
  "width": 1024,
  "height": 1024,
  "aspectRatio": "1:1",
  "guidanceScale": 12,
  "seed": 42,
  "creditCost": 5,
  "visibility": "public",
  "published": true,
  "publishedAt": "2025-11-25T06:00:00Z",
  "likes": 42,
  "comments": 8,
  "remixes": 3,
  "tags": ["cyberpunk", "character", "warrior"],
  "metadata": {
    "generationTime": 7.3,
    "modelVersion": "imagen3-v2.1"
  },
  "createdAt": "2025-11-25T05:59:52Z",
  "updatedAt": "2025-11-25T06:00:00Z"
}
```

## Quick Start Examples

### Generate Basic Avatar

<CodeGroup>
  ```javascript Node.js theme={null}
  const response = await fetch('https://api.percify.io/v1/avatars/generate', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.PERCIFY_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      prompt: 'fantasy elf warrior, forest background, magical aura',
      model: 'flux',
      aspectRatio: '1:1'
    })
  });

  const avatar = await response.json();
  console.log(`Avatar ID: ${avatar.id}`);
  ```

  ```python Python theme={null}
  import os
  import requests

  response = requests.post(
      'https://api.percify.io/v1/avatars/generate',
      headers={
          'Authorization': f'Bearer {os.environ["PERCIFY_API_KEY"]}',
          'Content-Type': 'application/json'
      },
      json={
          'prompt': 'fantasy elf warrior, forest background, magical aura',
          'model': 'flux',
          'aspectRatio': '1:1'
      }
  )

  avatar = response.json()
  print(f"Avatar ID: {avatar['id']}")
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.percify.io/v1/avatars/generate \
    -H "Authorization: Bearer $PERCIFY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "fantasy elf warrior, forest background, magical aura",
      "model": "flux",
      "aspectRatio": "1:1"
    }'
  ```
</CodeGroup>

### Get Avatar Status

```bash theme={null}
curl -X GET https://api.percify.io/v1/avatars/avatar_abc123 \
  -H "Authorization: Bearer $PERCIFY_API_KEY"
```

### List Your Avatars

```bash theme={null}
curl -X GET https://api.percify.io/v1/avatars?limit=20&offset=0 \
  -H "Authorization: Bearer $PERCIFY_API_KEY"
```

## Generation Status

Avatars go through several status stages:

| Status       | Description                 | Next Action            |
| ------------ | --------------------------- | ---------------------- |
| `queued`     | Waiting in generation queue | Poll for status update |
| `processing` | AI model is generating      | Continue polling       |
| `completed`  | Generation successful       | Image URLs available   |
| `failed`     | Generation failed           | Check error details    |

## Error Responses

Standard error format:

```json theme={null}
{
  "error": {
    "code": "insufficient_credits",
    "message": "Not enough credits to generate avatar. Required: 5, Available: 2",
    "details": {
      "required": 5,
      "available": 2
    }
  }
}
```

Common error codes:

* `invalid_request` - Missing or invalid parameters
* `authentication_required` - Missing or invalid API key
* `insufficient_credits` - Not enough credits for operation
* `rate_limit_exceeded` - Too many requests
* `content_policy_violation` - Prompt violates content policy
* `avatar_not_found` - Avatar ID doesn't exist
* `unauthorized_access` - Can't access another user's private avatar

## Rate Limits

| Tier       | Requests/minute | Concurrent Generations |
| ---------- | --------------- | ---------------------- |
| Free       | 10              | 1                      |
| Pro        | 60              | 5                      |
| Enterprise | 300             | 20                     |

Rate limit headers included in responses:

```
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1700000000
```

## Webhooks

Subscribe to avatar events:

```json theme={null}
{
  "event": "avatar.completed",
  "data": {
    "avatarId": "avatar_abc123",
    "status": "completed",
    "imageUrl": "https://cdn.percify.io/avatars/avatar_abc123.png"
  },
  "timestamp": "2025-11-25T06:00:00Z"
}
```

Available events:

* `avatar.completed` - Generation finished successfully
* `avatar.failed` - Generation failed
* `avatar.published` - Avatar published to feed
* `avatar.liked` - Someone liked your avatar
* `avatar.commented` - New comment on avatar

## Best Practices

<AccordionGroup>
  <Accordion icon="rotate" title="Polling for Completion">
    ```javascript theme={null}
    async function waitForAvatar(avatarId) {
      const maxAttempts = 30;
      const pollInterval = 2000; // 2 seconds
      
      for (let i = 0; i < maxAttempts; i++) {
        const response = await fetch(
          `https://api.percify.io/v1/avatars/${avatarId}`,
          {
            headers: {
              'Authorization': `Bearer ${process.env.PERCIFY_API_KEY}`
            }
          }
        );
        
        const avatar = await response.json();
        
        if (avatar.status === 'completed') {
          return avatar;
        } else if (avatar.status === 'failed') {
          throw new Error(`Generation failed: ${avatar.error}`);
        }
        
        await new Promise(resolve => setTimeout(resolve, pollInterval));
      }
      
      throw new Error('Avatar generation timed out');
    }
    ```
  </Accordion>

  <Accordion icon="key" title="Idempotency">
    Use idempotency keys for safe retries:

    ```bash theme={null}
    curl -X POST https://api.percify.io/v1/avatars/generate \
      -H "Authorization: Bearer $PERCIFY_API_KEY" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: unique-key-123" \
      -d '{"prompt": "..."}'
    ```
  </Accordion>

  <Accordion icon="code" title="Error Handling">
    ```javascript theme={null}
    try {
      const response = await fetch('https://api.percify.io/v1/avatars/generate', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ prompt, model })
      });
      
      if (!response.ok) {
        const error = await response.json();
        
        if (error.error.code === 'insufficient_credits') {
          // Handle low credits
          console.log('Please purchase more credits');
        } else if (error.error.code === 'rate_limit_exceeded') {
          // Wait and retry
          const resetTime = response.headers.get('X-RateLimit-Reset');
          console.log(`Rate limited until ${new Date(resetTime * 1000)}`);
        } else {
          throw new Error(error.error.message);
        }
      }
      
      const avatar = await response.json();
      return avatar;
    } catch (error) {
      console.error('Avatar generation failed:', error);
      throw error;
    }
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={3}>
  <Card title="Generate Avatar" icon="plus" href="/api-reference/avatars/generate">
    Create new avatars
  </Card>

  <Card title="Manage Avatars" icon="folder" href="/api-reference/avatars/list">
    List and organize
  </Card>

  <Card title="Publish Avatar" icon="share" href="/api-reference/avatars/publish">
    Share with community
  </Card>
</CardGroup>

## Support

Questions about the Avatar API? Check our [FAQ](/percify/faq) or contact [support@percify.io](mailto:support@percify.io).
