What You’ll Build
This tutorial walks you through building a FastAPI backend application from scratch, implementing Profy OAuth login, SQLAlchemy Token persistence, per-use billing event reporting, and streaming AI model calls.Prerequisites
Profy Developer Account
Registered a Profy account and created an App in the developer dashboard to obtain your Client ID and Client Secret
Development Environment
Python 3.10+, pip, basic FastAPI and async/await experience
Step 1: Project Setup
.env file for credentials:
.env
Step 2: Database Configuration
Use SQLAlchemy async engine + SQLite (replace with PostgreSQL for production):models.py
models.py
create_token_model automatically creates a table with user_id, access_token, refresh_token, expires_at, and scope columns. No manual schema definition needed.Step 3: Initialize the SDK
config.py
Step 4: OAuth Login Flow
main.py
Step 5: Protecting Routes
Use FastAPI dependency injection to automatically load and validate Tokens:dependencies.py
main.py
Step 6: Report Billing Events
main.py
idempotency_key ensures the same request won’t be charged twice on retry. It’s recommended to generate it on the client side or use a business-unique identifier.Step 7: Call AI Models
Usehttpx to directly call Profy’s OpenAI-compatible endpoint with SSE streaming responses:
main.py
Step 8: Error Handling Middleware
All SDK exceptions are typed subclasses that can be intercepted uniformly via FastAPI exception handlers:main.py
Complete Project
Full code for the three core files:models.py
config.py
dependencies.py
main.py
requirements.txt contents:
requirements.txt
Deployment Recommendations
Multi-Worker Deployment
Use
uvicorn main:app --workers 4 or pair with Gunicorn: gunicorn main:app -k uvicorn.workers.UvicornWorker -w 4 for production. SQLite is not suitable for multi-worker setups — switch to PostgreSQL.Environment Variable Management
Inject credentials via Kubernetes Secrets or cloud platform environment variables in production — don’t use
.env files. Set secure=True for cookies.Database Migrations
Replace the
create_async_engine connection string with postgresql+asyncpg://... for production. Use Alembic for schema migrations — don’t use create_all in production.Reverse Proxy
Run behind Nginx / Caddy to handle HTTPS termination and static assets. Ensure
X-Forwarded-Proto is correctly passed to generate accurate callback URLs.Next Steps
Next.js Full-Stack Integration
Build a Next.js full-stack application with the TypeScript SDK
Per-Use Billing SaaS
PER_USE mode: fixed-price per-use billing
Token Management Best Practices
Concurrent refresh, secure storage, degradation strategies
SDK Complete Guide
Dual-language API reference and Token persistence

