Skip to content

A fast, semantic avatar API service built on Cloudflare Workers that serves curated avatar images based on natural language descriptions. Think DiceBear, but with real images and intelligent search.

SharanRP/facegen-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

34 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Facegen API Service

A fast, semantic avatar API service built on Cloudflare Workers that serves curated avatar images based on natural language descriptions. Think DiceBear, but with real images and intelligent search.

🎯 What This Project Does

The Facegen API Service allows users to get avatar images by simply describing what they want in natural language. Instead of using random seeds or complex parameters, users can request avatars like:

  • ?description=professional β†’ Returns a professional business avatar
  • ?description=doctor-smile β†’ Returns a friendly medical professional avatar
  • ?description=creative-designer β†’ Returns an artistic/creative avatar

The service uses semantic search to match user descriptions with a curated database of avatar images stored in Appwrite, then serves them globally via Cloudflare's edge network.

🌐 Live API

Production URL: https://facegen-api.avatar-api.workers.dev

Quick Test

<img src="https://facegen-api.avatar-api.workers.dev/avatar?description=professional" alt="Avatar" />

πŸ“‘ API Endpoints

GET /avatar

Returns an avatar image based on description.

Parameters:

  • description (required): Natural language description of desired avatar

Example:

GET /avatar?description=professional-business
GET /avatar?description=doctor-healthcare  
GET /avatar?description=creative-designer

Response: PNG image (256x256 pixels)

GET /health

Health check endpoint for monitoring.

Response:

{
  "status": "healthy",
  "timestamp": 1759520000000,
  "services": {
    "database": {"status": "healthy"},
    "storage": {"status": "healthy"}
  }
}

GET /metrics

Performance and usage metrics.

Response:

{
  "timestamp": 1759520000000,
  "metrics": {
    "requests_total": 1234,
    "cache_hit_rate": 0.85,
    "avg_response_time": 45
  }
}

πŸ”§ Environment Variables

Required (Appwrite Configuration)

APPWRITE_PROJECT_ID=your_project_id
APPWRITE_ENDPOINT=https://nyc.cloud.appwrite.io/v1
APPWRITE_DATABASE_ID=your_database_id
APPWRITE_COLLECTION_ID=avatars
APPWRITE_BUCKET_ID=your_bucket_id
APPWRITE_API_KEY=your_api_key

Optional (Performance Tuning)

RATE_LIMIT_PER_MINUTE=100
RATE_LIMIT_PER_HOUR=1000
CACHE_TTL_SUCCESS=3600
CACHE_TTL_ERROR=300
CIRCUIT_BREAKER_THRESHOLD=5
CIRCUIT_BREAKER_TIMEOUT=30000
LOG_LEVEL=info

πŸš€ Quick Start

1. Clone and Install

git clone <your-repo>
cd avatar-api-service
npm install

2. Environment Setup

# Copy environment template
cp .env.example .env

# Edit .env with your Appwrite credentials
# Get these from: https://cloud.appwrite.io

3. Appwrite Setup

  1. Create project in Appwrite Cloud
  2. Create database with collection named "avatars"
  3. Create storage bucket for avatar images
  4. Generate API key with Database:Read and Storage:Read permissions
  5. Upload avatar images and create corresponding documents

4. Local Development

# Setup Cloudflare Workers and KV namespaces
npm run setup

# Start development server
npm run dev

# Test the API
curl http://localhost:8787/health
curl "http://localhost:8787/avatar?description=professional"

5. Deploy to Production

npm run deploy:production

πŸ—οΈ Architecture

  • Platform: Cloudflare Workers (Edge Computing)
  • Database: Appwrite (Document database for avatar metadata)
  • Storage: Appwrite Storage (PNG image files)
  • Caching: Cloudflare Edge Cache (Global CDN)
  • Rate Limiting: Cloudflare KV (Distributed rate limiting)

πŸ” How Search Works

  1. User Query: ?description=professional-doctor
  2. Keyword Extraction: ["professional", "doctor"]
  3. Database Search: Searches Tags field in Appwrite collection
  4. Enhanced Ranking: Uses semantic matching with synonyms
  5. Image Delivery: Streams PNG image from Appwrite storage
  6. Edge Caching: Cached globally for fast subsequent requests

πŸ“Š Database Schema

Your Appwrite collection should have these attributes:

Field Type Size Required Description
Description String 500 Yes Human-readable description
Tags String 1000 Yes Comma-separated searchable keywords
fileId String 100 Yes Reference to image file in storage
bucketId String 100 Yes Storage bucket identifier
width Integer - Yes Image width in pixels
height Integer - Yes Image height in pixels

Indexes:

  • tags_index (Fulltext on Tags)
  • size_index (Key on width, height)

πŸ› οΈ Development Commands

# Setup (first time only)
npm run setup

# Development
npm run dev

# Build and test
npm run build
npm run test

# Code quality
npm run lint
npm run format

# Deployment
npm run deploy              # Deploy to development
npm run deploy:staging      # Deploy to staging
npm run deploy:production   # Deploy to production

πŸ” Security & Performance

  • Rate Limiting: 100 requests/minute, 1000 requests/hour per IP
  • Input Validation: Sanitizes all user input
  • CORS Enabled: Cross-origin requests supported
  • Circuit Breaker: Protects against backend failures
  • Edge Caching: 1-hour cache for images, 5-minute cache for errors
  • Global CDN: Served from 200+ Cloudflare locations worldwide

πŸ“ˆ Monitoring

  • Health Checks: /health endpoint for uptime monitoring
  • Metrics: /metrics endpoint for performance data
  • Correlation IDs: Every request gets a unique tracking ID
  • Cloudflare Analytics: Built-in request analytics and performance metrics

🌍 Deployment Environments

  • Development: http://localhost:8787 (local testing)
  • Staging: https://facegen-api-staging.avatar-api.workers.dev
  • Production: https://facegen-api.avatar-api.workers.dev

🎨 Usage Examples

HTML

<img src="https://facegen-api.avatar-api.workers.dev/avatar?description=professional" 
     alt="Professional Avatar" width="256" height="256" />

React

function Avatar({ userType }) {
  return (
    <img 
  src={`https://facegen-api.avatar-api.workers.dev/avatar?description=${userType}`}
      alt={`${userType} avatar`}
      width="256" 
      height="256"
    />
  );
}

CSS

.profile-pic {
  background-image: url('https://facegen-api.avatar-api.workers.dev/avatar?description=professional');
  width: 256px;
  height: 256px;
  border-radius: 50%;
}

πŸ“„ License

MIT License - see LICENSE file for details


Built with ❀️ using Cloudflare Workers, Appwrite, and TypeScript

About

A fast, semantic avatar API service built on Cloudflare Workers that serves curated avatar images based on natural language descriptions. Think DiceBear, but with real images and intelligent search.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published