Short answer
Call get_price_async() in async def routes and get_price() in def routes. Add every quote.set_cookie value to the response you actually return, because an injected Response is ignored when you return a TemplateResponse or RedirectResponse. At checkout, price again, pass quote.price and the whole quote.metadata to Stripe, and redirect with status 303.
- A sync get_price() inside async def can block the event loop for up to 500 ms while a cold process fetches its config.
- FastAPI copies headers from an injected Response only when the route returns plain data, so apply cookies to a TemplateResponse or RedirectResponse directly.
- RedirectResponse defaults to 307, which makes the browser repeat the POST against Stripe; pass status_code=303.
- The visitor cookie is SameSite=Lax, so a frontend on another site never sends it with fetch(); serve the API from the same site.
FastAPI price tests fail in two quiet ways. A sync SDK call inside async def can stall the event loop for up to 500 ms while a cold process fetches its config, and cookies set on an injected Response never reach the browser when the route returns a TemplateResponse. Neither raises an error. This guide wires Leverprice and Stripe Checkout into FastAPI so neither happens.
The code targets FastAPI 0.163 on Starlette 1.10, stripe-python 17 and the leverprice package for Python 3.9+.
How does price testing work in a FastAPI app?
The price is decided on your server. get_price_async() reads the visitor's __pp cookie and user agent from the Starlette Request, picks their price from a signed config held in memory, checks it against bounds you set in code and returns a quote: price in minor units (2900 is $29.00), currency, a signed metadata dict and a list of Set-Cookie values. No Leverprice JavaScript reaches the browser.
The checkout route asks again and gets the same answer, because the signed cookie comes back with the browser. Stripe later confirms the payment to Leverprice with a signed webhook. The case for running all of this on the server is in server-side price testing.
How do I set up the client in FastAPI?
pip install leverprice "stripe[async]" jinja2LEVERPRICE_SECRET_KEY=pp_sk_test_...
STRIPE_SECRET_KEY=sk_test_...stripe[async] adds httpx, which stripe-python uses for its _async methods, per the stripe-python README. Create both clients once per process:
import os
from leverprice import Leverprice
from stripe import StripeClient
leverprice = Leverprice(
secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"),
products={
# Guardrails in minor units: a price outside them is never returned.
"pro": {"currency": "usd", "fallback_price": 2900, "min_price": 1900, "max_price": 4900},
},
)
stripe_client = StripeClient(os.environ["STRIPE_SECRET_KEY"])Then fetch the config before the first visitor arrives and flush queued exposures on shutdown, in the lifespan handler FastAPI recommends over startup events:
import asyncio
from contextlib import asynccontextmanager, suppress
from fastapi import FastAPI
from pricing import leverprice
@asynccontextmanager
async def lifespan(app: FastAPI):
with suppress(TimeoutError):
async with asyncio.timeout(2): # never hold up startup for long
await leverprice.preload_async()
yield
await leverprice.close_async()
app = FastAPI(lifespan=lifespan)fallback_price is what visitors pay when Leverprice cannot answer: no key, LEVERPRICE_DISABLED=1, or no signed config within 500 ms. get_price_async() never raises for those reasons, only for a product key missing from products. The SDK docs list the remaining options.
Should I call get_price or get_price_async?
Match the route. FastAPI runs a plain def route "in an external threadpool that is then awaited", per its concurrency guide, and calls an async def route on the event loop itself:
| Route | Price call | Purchase call |
|---|---|---|
async def | await leverprice.get_price_async(...) | await leverprice.track_purchase_async(...) |
def | leverprice.get_price(...) | leverprice.track_purchase(...) |
The sync methods wait on locks and network: get_price() waits up to 500 ms when no config is loaded yet, and track_purchase() sends right away. Inside async def, that wait freezes every other request on the worker. The async variants never block the loop.
How do I send the price and its cookie?
It depends on what the route returns. For plain data, inject a Response and add the cookies to it; FastAPI copies its headers into the JSON response, as the response headers docs describe. For templates and redirects, add the cookies to the object you return:
from fastapi import Request, Response
from fastapi.templating import Jinja2Templates
from leverprice import apply_cookies
templates = Jinja2Templates(directory="templates")
@app.get("/api/price")
async def price(request: Request, response: Response):
quote = await leverprice.get_price_async("pro", request)
apply_cookies(response, quote) # copied into the JSON response
return {"price": quote.price, "currency": quote.currency}
@app.get("/pricing")
async def pricing(request: Request):
quote = await leverprice.get_price_async("pro", request)
page = templates.TemplateResponse(request=request, name="pricing.html", context={"quote": quote})
return apply_cookies(page, quote) # an injected Response would be ignored hereThe split comes from FastAPI's request handler: when a route returns a Response instance, FastAPI sends it as is and copies headers from the injected Response only in the branch that builds a response from plain data (source). Set the cookie on the wrong object and every page view becomes a new visitor, so the price can change on reload.
Pass user_id= for signed-in customers, from whatever auth dependency you already use. It puts a customer in the same bucket on every device, and only an HMAC of it leaves your server.
How do I charge the same price with Stripe Checkout?
Price the checkout on the server again and charge quote.price; ignore any amount the client sends. Stripe's price_data takes the amount inline, so there is no Stripe Price per tested price:
from fastapi.responses import RedirectResponse
from pricing import stripe_client
@app.post("/checkout")
async def checkout(request: Request):
quote = await leverprice.get_price_async("pro", request)
session = await stripe_client.v1.checkout.sessions.create_async({
"mode": "payment",
"line_items": [{
"quantity": 1,
"price_data": {
"currency": quote.currency,
"unit_amount": quote.price,
"product_data": {"name": "Pro"},
},
}],
"metadata": quote.metadata, # signed attribution: pass it whole
"payment_intent_data": {"metadata": quote.metadata},
"success_url": str(request.url_for("thanks")),
"cancel_url": str(request.url_for("pricing")),
})
return apply_cookies(RedirectResponse(session.url, status_code=303), quote)
@app.get("/thanks")
async def thanks(request: Request):
return templates.TemplateResponse(request=request, name="thanks.html")Mind the status code. RedirectResponse "uses a 307 status code (Temporary Redirect) by default" (custom responses), and a 307 makes the browser repeat the form's POST against Stripe's page. A 303 turns it into the GET Stripe expects. quote.metadata holds pp_exp, pp_var, pp_vid and pp_sig, signed together, so it goes into Stripe whole.
Selling a subscription? Use "mode": "subscription", add "recurring": {"interval": "month"} to price_data, and move the metadata copy into subscription_data, because the Checkout Session API accepts payment_intent_data only in payment mode. Leverprice's Stripe verification covers one-time payments, so a subscription's first payment must be reported with track_purchase_async() from your own webhook route; it shows as unverified. Renewals never count toward a test.
The other providers work the same way: charge quote.price, pass quote.metadata whole. Polar takes an ad-hoc price per checkout, and Leverprice verifies one-time orders and a subscription's first payment. Lemon Squeezy takes custom_price in cents, though it stops processing payments on March 31, 2027. Dodo Payments accepts a custom amount on pay-what-you-want products, with one-time payments verified.
What if my frontend lives on another domain?
Then the visitor cookie may never come back. It is set with SameSite=Lax, and MDN lists requests made with fetch() among the cross-site requests that exclude such a cookie. A React app on myapp.vercel.app calling api.myapp.com is cross-site, so each call looks like a new visitor and the price can change on every load.
Keep the page and the API on one site: myapp.com with api.myapp.com works, because they share a registrable domain. Then fetch with credentials: "include" and enable allow_credentials=True in CORSMiddleware; FastAPI's CORS docs note that origins cannot be the wildcard ["*"] once credentials are allowed. Set cookie_domain="myapp.com" on the client only if several subdomains price the same visitor.
Can I show a different price per country?
Yes. With regional prices on in the dashboard, each country gets a price you set by hand or one derived from its tier (5 tiers by World Bank price level), charged in its own currency. Example: a visitor from India sees ₹999 while a visitor from the US sees $29. The client decides where the country comes from and which prices may pass:
leverprice = Leverprice(
secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"),
country_header="cf-ipcountry", # set by Cloudflare; on Vercel: x-vercel-ip-country
products={
"pro": {
"currency": "usd", "fallback_price": 2900, "min_price": 1900, "max_price": 4900,
"regional": { # currencies you accept, each with hard bounds
"usd": {"min_price": 800, "max_price": 4900},
"eur": {"min_price": 1100, "max_price": 6000},
"inr": {"min_price": 48000, "max_price": 230000},
},
},
},
)There is no default header on purpose: one that visitors can send themselves would let them pick their price. Without a CDN header, pass country= from your own lookup. Currencies you didn't list, prices outside their bounds, bots and unknown countries all get the standard price. The checkout already passes quote.currency, so Stripe charges in the visitor's currency; confirm your account supports each one, and format amounts with each currency's decimals (JPY has none, per Stripe's zero-decimal list).
How does Leverprice verify revenue from Stripe?
Stripe sends signed webhooks to Leverprice directly. In the dashboard, open Payments and connect Stripe to get an endpoint URL; add it in Stripe for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded; paste that endpoint's signing secret back into Leverprice. A signing secret can confirm events but cannot move money, so an API key never goes there. The Stripe integration page has the details, and verified revenue explains why the signature matters.
You need your own route only if you cannot add an endpoint or you sell subscriptions. What it reports is labeled unverified and never overrides a verified purchase:
import os
import stripe
PAID = {"checkout.session.completed", "checkout.session.async_payment_succeeded"}
@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
payload = await request.body()
try:
event = stripe_client.construct_event(
payload, request.headers.get("stripe-signature"), os.environ["STRIPE_WEBHOOK_SECRET"]
)
except (ValueError, stripe.SignatureVerificationError):
return Response(status_code=400)
if event.type in PAID and event.data.object.payment_status == "paid":
session = event.data.object
tax = session.total_details.amount_tax if session.total_details else 0
await leverprice.track_purchase_async(
provider="stripe",
order_id=session.payment_intent or session.invoice, # invoice: subscription mode
amount=session.amount_total - tax,
currency=session.currency,
metadata=session.metadata.to_dict(),
timestamp=event.created,
)
return Response(status_code=200)Read the raw bytes with await request.body() and verify them before any parsing; don't declare a Pydantic body for this route. Keep .to_dict(): since stripe-python 15.0.0, Stripe objects are not dicts, and the SDK reads no attribution from one.
How do I test it locally?
Run fastapi dev main.py (or uvicorn main:app --reload) with test keys and a test-mode Stripe endpoint connected in Leverprice, then check by hand:
- Load the pricing page, note the price, reload. It must not change.
- Click Buy. Stripe's amount must equal the page's price.
- Pay with a card from Stripe's testing docs, such as 4242 4242 4242 4242.
- Unset
LEVERPRICE_SECRET_KEYand restart: the fallback price appears with reason"disabled".
In pytest, Starlette's TestClient sends the user agent testclient, which counts as a person, while httpx.AsyncClient sends python-httpx/…, which counts as a bot and gets the standard price. Set a browser user agent, or pass bot=False in tests. On plain HTTP, the Secure cookie survives on localhost only, per MDN; for a phone on your LAN, set cookie_secure=False in development.
What changes in production?
Swap in pp_sk_live_… and your live Stripe key, and connect the live-mode Stripe endpoint in Leverprice with its own signing secret. With --workers 4, each worker process runs its own lifespan, so each preloads and closes its own client.
Behind a load balancer, check request.url_for(). Uvicorn trusts X-Forwarded-Proto only from the IPs in --forwarded-allow-ips, which defaults to 127.0.0.1 and ::1 (settings); a proxy on another address leaves your Stripe success URLs on http. To switch the test off, set LEVERPRICE_DISABLED=1 and restart: every visitor gets your fallback price, with no network calls.
What breaks most often?
| Symptom | Likely cause | Fix |
|---|---|---|
| Price changes on reload of an HTML page | Cookies set on an injected Response, then a TemplateResponse returned | Apply cookies to the returned object |
| Error page right after Buy | RedirectResponse sent 307, so the browser re-posted | status_code=303 |
| Slow first requests, stalls under load | Sync get_price() in async def | get_price_async() and lifespan preload |
| Price changes on every load of a separate frontend | Cross-site fetch() drops the SameSite=Lax cookie | Same-site API, credentials: "include" |
reason is "bot" in pytest | httpx.AsyncClient user agent | Browser user agent, or bot=False |
| http success URLs in production | Proxy IP not in --forwarded-allow-ips | Add it |
| Purchases from your own route lack attribution | StripeObject passed as metadata | session.metadata.to_dict() |
Frequently asked questions
Does this work in plain Starlette?
Yes. FastAPI's Request and responses are Starlette's, so get_price_async(request) and apply_cookies() work the same in a Starlette app. For a WSGI app, the Flask guide covers the sync client.
How do I price monthly and yearly plans in one request?
Call get_price_async() once per product key with the same Request object, then apply both quotes' cookies. The quotes share one visitor, and the last cookie carries every assignment.
Can a single-page app call /api/price?
Yes, and that is a good fit when HTML is cached or static. The exposure is logged when the route runs, so call it when the price is about to appear, not on hover or for a hidden tab.
What happens when the test ends?
You lock in the winner in the dashboard, and every visitor gets it within about a second. The FastAPI code doesn't change.