references/EXAMPLE-fastapi.md · 24000
session_token") return response
@router.get("/dashboard", response_class=HTMLResponse) async def dashboard( request: Request, current_user: RequiredUser, ): """Dashboard with feature flag demonstration.""" capture("dashboard_viewed", properties={"is_staff": current_user.is_staff})
# Check feature flag
show_new_feature = posthog.feature_enabled(
"new-dashboard-feature",
current_user.email,
person_properties={
"email": current_user.email,
"is_staff": current_user.is_staff,
},
)
# Get feature flag payload
feature_config = posthog.get_feature_flag_payload(
"new-dashboard-feature", current_user.email
)
return templates.TemplateResponse(
request,
"dashboard.html",
{
"current_user": current_user,
"show_new_feature": show_new_feature,
"feature_config": feature_config,
},
)
@router.get("/burrito", response_class=HTMLResponse) async def burrito( request: Request, current_user: RequiredUser, burrito_count: Annotated[int, Cookie()] = 0, ): """Burrito consideration tracker page.""" return templates.TemplateResponse( request, "burrito.html", {"current_user": current_user, "burrito_count": burrito_count}, )
@router.get("/profile", response_class=HTMLResponse) async def profile(request: Request, current_user: RequiredUser): """User profile page.""" capture("profile_viewed")
return templates.TemplateResponse(
request, "profile.html", {"current_user": current_user}
)
@router.post("/profile", response_class=HTMLResponse) async def update_profile( request: Request, db: DbSession, current_user: RequiredUser, name: Annotated[str, Form()], ): """Handle profile update.""" fields_changed = current_user.update_profile(db, name=name)
if fields_changed:
capture(
"profile_updated",
properties={
"username": current_user.email,
"fields_changed": fields_changed,
},
)
return templates.TemplateResponse(
request,
"profile.html",
{
"current_user": current_user,
"success": "Profile updated" if fields_changed else None,
},
)
---
## app/templates/base.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}PostHog FastAPI Example{% endblock %}</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
line-height: 1.6;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
nav {
background: #1d4ed8;
padding: 15px 20px;
margin-bottom: 30px;
}
nav a {
color: white;
text-decoration: none;
margin-right: 20px;
}
nav a:hover {
text-decoration: underline;
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h1, h2, h3 {
margin-bottom: 15px;
color: #1d4ed8;
}
button, .btn {
background: #1d4ed8;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
display: inline-block;
text-decoration: none;
}
button:hover, .btn:hover {
background: #1e40af;
}
button.danger {
background: #dc2626;
}
button.danger:hover {
background: #b91c1c;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
}
.messages {
margin-bottom: 20px;
}
.message {
padding: 10px 15px;
border-radius: 5px;
margin-bottom: 10px;
}
.message.error {
background: #fee2e2;
color: #dc2626;
}
.message.success {
background: #d1fae5;
color: #059669;
}
.feature-flag {
background: #fef3c7;
border: 2px dashed #f59e0b;
padding: 15px;
border-radius: 8px;
margin: 20px 0;
}
code {
background: #f3f4f6;
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}
pre {
background: #1e293b;
color: #e2e8f0;
padding: 16px;
border-radius: 8px;
overflow-x: auto;
font-size: 13px;
}
.count {
font-size: 48px;
font-weight: bold;
color: #1d4ed8;
text-align: center;
padding: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #eee;
}
th {
background: #f8fafc;
font-weight: 600;
}
</style>
</head>
<body>
{% if current_user %}
<nav>
<a href="/dashboard">Dashboard</a>
<a href="/burrito">Burrito</a>
<a href="/profile">Profile</a>
<a href="/logout" style="float: right;">Logout ({{ current_user.email }})</a>
</nav>
{% endif %}
<div class="container">
{% if error %}
<div class="messages">
<div class="message error">{{ error }}</div>
</div>
{% endif %}
{% if success %}
<div class="messages">
<div class="message success">{{ success }}</div>
</div>
{% endif %}
{% block content %}{% endblock %}
</div>
{% block scripts %}{% endblock %}
</body>
</html>
app/templates/burrito.html
{% extends "base.html" %}
{% block title %}Burrito - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>Burrito Consideration Tracker</h1>
<p>This page demonstrates custom event tracking with PostHog.</p>
<div class="count" id="burrito-count">{{ burrito_count }}</div>
<p style="text-align: center; color: #666;">Times you've considered a burrito</p>
<div style="text-align: center; margin-top: 20px;">
<button onclick="considerBurrito()">Consider a Burrito</button>
</div>
</div>
<div class="card">
<h3>Code Example</h3>
<pre>
# API endpoint captures the event
with new_context():
identify_context(current_user.email)
capture('burrito_considered', properties={
'total_considerations': burrito_count
})</pre>
</div>
{% endblock %}
{% block scripts %}
<script>
async function considerBurrito() {
try {
const response = await fetch('/api/burrito/consider', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.success) {
document.getElementById('burrito-count').textContent = data.count;
}
} catch (error) {
console.error('Error:', error);
}
}
</script>
{% endblock %}
app/templates/dashboard.html
{% extends "base.html" %}
{% block title %}Dashboard - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>Dashboard</h1>
<p>Welcome back, {{ current_user.email }}!</p>
</div>
<div class="card">
<h2>Feature Flags</h2>
{% if show_new_feature %}
<div class="feature-flag">
<strong>New Feature Enabled!</strong>
<p>You're seeing this because the <code>new-dashboard-feature</code> flag is enabled for you.</p>
{% if feature_config %}
<p><strong>Feature Configuration:</strong></p>
<pre>{{ feature_config | tojson(indent=2) }}</pre>
{% endif %}
</div>
{% else %}
<p>The <code>new-dashboard-feature</code> flag is not enabled for your account.</p>
{% endif %}
<h3 style="margin-top: 20px;">Code Example</h3>
<pre>
# Check if feature flag is enabled
show_new_feature = posthog.feature_enabled(
'new-dashboard-feature',
user_id,
person_properties={
'email': current_user.email,
'is_staff': current_user.is_staff
}
)
# Get feature flag payload
feature_config = posthog.get_feature_flag_payload(
'new-dashboard-feature',
user_id
)</pre>
</div>
{% endblock %}
app/templates/errors/404.html
{% extends "base.html" %}
{% block title %}Page Not Found - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>404 - Page Not Found</h1>
<p>The page you're looking for doesn't exist.</p>
<a href="/" class="btn">Go Home</a>
</div>
{% endblock %}
app/templates/errors/500.html
{% extends "base.html" %}
{% block title %}Server Error - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>500 - Internal Server Error</h1>
<p>Something went wrong on our end. Please try again later.</p>
<a href="/" class="btn">Go Home</a>
</div>
{% endblock %}
app/templates/home.html
{% extends "base.html" %}
{% block title %}Login - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>Welcome to PostHog FastAPI Example</h1>
<p>This example demonstrates how to integrate PostHog with a FastAPI application.</p>
<form method="POST">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
<p style="margin-top: 16px; font-size: 14px; color: #666;">
Don't have an account? <a href="/signup">Sign up here</a>
</p>
<p style="font-size: 14px; color: #666;">
<strong>Tip:</strong> Default credentials are [email protected]/admin
</p>
</div>
<div class="card">
<h2>Features Demonstrated</h2>
<ul style="margin-left: 20px; color: #666;">
<li>User registration and identification</li>
<li>Event tracking</li>
<li>Feature flags</li>
<li>Error tracking</li>
<li>Group analytics</li>
</ul>
</div>
{% endblock %}
app/templates/profile.html
{% extends "base.html" %}
{% block title %}Profile - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>Your Profile</h1>
<p>This page demonstrates profile updates and report generation with PostHog.</p>
{% if success %}
<div class="message success">{{ success }}</div>
{% endif %}
<form method="POST" action="/profile">
<table>
<tr>
<th>Email</th>
<td>{{ current_user.email }}</td>
</tr>
<tr>
<th>Name</th>
<td>
<input type="text" name="name" value="{{ current_user.name or '' }}" placeholder="Enter your name">
</td>
</tr>
<tr>
<th>Date Joined</th>
<td>{{ current_user.date_joined.strftime('%Y-%m-%d %H:%M') }}</td>
</tr>
<tr>
<th>Login Count</th>
<td>{{ current_user.login_count }}</td>
</tr>
<tr>
<th>Staff Status</th>
<td>{{ 'Yes' if current_user.is_staff else 'No' }}</td>
</tr>
</table>
<button type="submit">Update Profile</button>
</form>
</div>
<div class="card">
<h2>Activity Reports</h2>
<p>Generate a report of your account activity:</p>
<div style="margin: 20px 0;">
<button onclick="generateReport('summary')">Summary Report</button>
<button onclick="generateReport('detailed')">Detailed Report</button>
</div>
<div id="report-result" style="display: none;" class="message"></div>
</div>
<div class="card">
<h2>Error Tracking Demo</h2>
<p>Click a button to trigger an error and see it captured in PostHog:</p>
<div style="margin: 20px 0;">
<button class="danger" onclick="triggerError('value')">
Trigger ValueError
</button>
<button class="danger" onclick="triggerError('key')">
Trigger KeyError
</button>
<button class="danger" onclick="triggerError('generic')">
Trigger Generic Error
</button>
</div>
<div id="error-result" style="display: none;" class="message"></div>
</div>
<div class="card">
<h3>Code Example</h3>
<pre>
try:
raise ValueError('Invalid value provided')
except Exception as e:
# Capture exception and event with user context
with new_context():
identify_context(current_user.email)
posthog.capture_exception(e)
capture('error_triggered', properties={
'error_type': 'value',
'error_message': str(e)
})</pre>
</div>
{% endblock %}
{% block scripts %}
<script>
async function triggerError(errorType) {
const resultDiv = document.getElementById('error-result');
try {
const formData = new FormData();
formData.append('error_type', errorType);
const response = await fetch('/api/trigger-error', {
method: 'POST',
body: formData
});
const data = await response.json();
resultDiv.style.display = 'block';
resultDiv.className = 'message ' + (data.success ? 'success' : 'error');
resultDiv.textContent = data.message + ': ' + data.error;
} catch (error) {
console.error('Error:', error);
resultDiv.style.display = 'block';
resultDiv.className = 'message error';
resultDiv.textContent = 'Request failed: ' + error.message;
}
}
async function generateReport(reportType) {
const resultDiv = document.getElementById('report-result');
try {
const formData = new FormData();
formData.append('report_type', reportType);
const response = await fetch('/api/reports/activity', {
method: 'POST',
body: formData
});
const data = await response.json();
resultDiv.style.display = 'block';
resultDiv.className = 'message success';
resultDiv.innerHTML = '<strong>' + data.report_type + ' report generated</strong> (' + data.row_count + ' rows)<br><pre>' + JSON.stringify(data.data, null, 2) + '</pre>';
} catch (error) {
console.error('Error:', error);
resultDiv.style.display = 'block';
resultDiv.className = 'message error';
resultDiv.textContent = 'Request failed: ' + error.message;
}
}
</script>
{% endblock %}
app/templates/signup.html
{% extends "base.html" %}
{% block title %}Sign Up - PostHog FastAPI Example{% endblock %}
{% block content %}
<div class="card">
<h1>Create an Account</h1>
<p>Sign up to explore the PostHog FastAPI integration example.</p>
<form method="POST">
<label for="email">Email *</label>
<input type="email" id="email" name="email" required>
<label for="password">Password *</label>
<input type="password" id="password" name="password" required>
<label for="password_confirm">Confirm Password *</label>
<input type="password" id="password_confirm" name="password_confirm" required>
<button type="submit">Sign Up</button>
</form>
<p style="margin-top: 16px; font-size: 14px; color: #666;">
Already have an account? <a href="/">Login here</a>
</p>
</div>
<div class="card">
<h2>PostHog Integration</h2>
<p>When you sign up, the following PostHog events are captured:</p>
<ul style="margin-left: 20px; color: #666;">
<li><code>identify_context()</code> - Associates your email with the context</li>
<li><code>tag()</code> - Sets person properties (email, etc.)</li>
<li><code>user_signed_up</code> event - Tracks the signup action</li>
</ul>
<h3 style="margin-top: 20px;">Code Example</h3>
<pre>
# After creating the user
with new_context():
identify_context(user.email)
tag('email', user.email)
tag('is_staff', user.is_staff)
tag('date_joined', user.date_joined.isoformat())
capture('user_signed_up', properties={'signup_method': 'form'})</pre>
</div>
{% endblock %}
requirements.txt
fastapi>=0.109.0
uvicorn>=0.27.0
sqlalchemy>=2.0.0
python-dotenv>=1.0.0
posthog>=3.0.0
pydantic>=2.0.0
pydantic-settings>=2.0.0
jinja2>=3.0.0
python-multipart>=0.0.9
werkzeug>=3.0.0
itsdangerous>=2.0.0
run.py
"""Development server entry point."""
import uvicorn
if __name__ == "__main__":
uvicorn.run("app.main:app", host="0.0.0.0", port=5002, reload=True)