Integrate with FastAPI
Add billing and payments to your FastAPI application.
Install
pip install commet-sdk fastapi uvicornuv add commet-sdk fastapi uvicornpoetry add commet-sdk fastapi uvicornConfigure
COMMET_API_KEY=ck_sandbox_xxximport os
from commet import Commet
commet = Commet(
api_key=os.environ["COMMET_API_KEY"],
environment="sandbox",
)Subscribe
from fastapi import APIRouter
from pydantic import BaseModel
from commet_client import commet
router = APIRouter(prefix="/billing")
class SubscribeRequest(BaseModel):
external_id: str
email: str
@router.post("/subscribe")
def subscribe(body: SubscribeRequest):
commet.customers.create(
email=body.email,
external_id=body.external_id,
)
subscription = commet.subscriptions.create(
external_id=body.external_id,
plan_code="pro",
)
return {"checkout_url": subscription.data["checkout_url"]}Check Access
@router.get("/subscription/{external_id}")
def get_subscription(external_id: str):
sub = commet.subscriptions.get(external_id)
return {"status": sub.data["status"]}
@router.get("/features/{feature}/{external_id}")
def check_feature(feature: str, external_id: str):
result = commet.features.check(code=feature, external_id=external_id)
return {"allowed": result.data["allowed"]}Track Usage
class UsageRequest(BaseModel):
external_id: str
@router.post("/usage")
def track_usage(body: UsageRequest):
commet.usage.track(
external_id=body.external_id,
feature="api_calls",
value=1,
)
return {"tracked": True}Usage is aggregated and billed at end of period.
Customer Portal
from fastapi.responses import RedirectResponse
@router.get("/portal")
def portal():
result = commet.portal.get_url(external_id="user_123")
return RedirectResponse(result.data["portal_url"])Webhooks
import os
from fastapi import APIRouter, Request, Response
from commet import Webhooks
router = APIRouter()
webhooks = Webhooks()
@router.post("/webhooks/commet")
async def handle_webhook(request: Request):
raw_body = await request.body()
payload = webhooks.verify_and_parse(
raw_body=raw_body.decode(),
signature=request.headers.get("x-commet-signature"),
secret=os.environ["COMMET_WEBHOOK_SECRET"],
)
if payload is None:
return Response(status_code=401)
if payload["event"] == "subscription.activated":
# handle activation
pass
return Response(status_code=200)Start Server
from fastapi import FastAPI
from routes.billing import router as billing_router
from routes.webhooks import router as webhooks_router
app = FastAPI()
app.include_router(billing_router)
app.include_router(webhooks_router)uvicorn main:app --port 3000Related
How is this guide?