McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Accept Payments with Paystack in FastAPI
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Accept Payments with Paystack in FastAPI

To accept Paystack payments in FastAPI, create async endpoints that call the Paystack API using httpx. Use Pydantic models for input validation. Initialize a transaction, return the authorization URL to your frontend, and verify the payment in a callback endpoint.

In this article

  1. 1. Project Setup
  2. 2. Pydantic Models
  3. 3. Initialize a Transaction
  4. 4. Handle the Callback
  5. 5. Verify Endpoint for Inline Popup
  6. 6. Production Checklist
  7. 7. Ship Payments Faster

Project Setup

pip install fastapi uvicorn httpx python-decouple

Create a .env file:

PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx
BASE_URL=http://localhost:8000
# main.py
from fastapi import FastAPI
from decouple import config

app = FastAPI()

PAYSTACK_SECRET = config('PAYSTACK_SECRET_KEY')
BASE_URL = config('BASE_URL')

Pydantic Models

# schemas.py
from pydantic import BaseModel, EmailStr

class PaymentRequest(BaseModel):
    email: EmailStr
    amount: float

class PaymentResponse(BaseModel):
    authorization_url: str
    access_code: str
    reference: str

class VerifyResponse(BaseModel):
    success: bool
    amount: float = 0
    currency: str = ''
    email: str = ''

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Initialize a Transaction

# main.py
import httpx
import uuid

@app.post('/api/pay', response_model=PaymentResponse)
async def initialize_payment(payment: PaymentRequest):
    reference = 'order_' + uuid.uuid4().hex[:12]

    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://api.paystack.co/transaction/initialize',
            json={
                'email': payment.email,
                'amount': int(payment.amount * 100),
                'reference': reference,
                'callback_url': BASE_URL + '/api/payment/callback',
            },
            headers={
                'Authorization': 'Bearer ' + PAYSTACK_SECRET,
                'Content-Type': 'application/json',
            },
        )

    data = response.json()

    if not data.get('status'):
        raise HTTPException(status_code=400, detail=data.get('message', 'Failed'))

    # TODO: Save order to database

    return PaymentResponse(
        authorization_url=data['data']['authorization_url'],
        access_code=data['data']['access_code'],
        reference=data['data']['reference'],
    )

Handle the Callback

# main.py
from fastapi import Query
from fastapi.responses import RedirectResponse, HTMLResponse

@app.get('/api/payment/callback')
async def payment_callback(reference: str = Query(None), trxref: str = Query(None)):
    ref = reference or trxref

    if not ref:
        return HTMLResponse('Missing reference', status_code=400)

    async with httpx.AsyncClient() as client:
        response = await client.get(
            'https://api.paystack.co/transaction/verify/' + ref,
            headers={'Authorization': 'Bearer ' + PAYSTACK_SECRET},
        )

    data = response.json()

    if data.get('status') and data['data']['status'] == 'success':
        amount = data['data']['amount'] / 100
        # TODO: Verify amount against database, mark order as paid
        return HTMLResponse(
            'Payment successful! Amount: ' + str(amount) + ' ' + data['data']['currency']
        )

    return HTMLResponse('Payment not successful', status_code=400)

Verify Endpoint for Inline Popup

@app.get('/api/verify', response_model=VerifyResponse)
async def verify_payment(reference: str):
    async with httpx.AsyncClient() as client:
        response = await client.get(
            'https://api.paystack.co/transaction/verify/' + reference,
            headers={'Authorization': 'Bearer ' + PAYSTACK_SECRET},
        )

    data = response.json()

    if data.get('status') and data['data']['status'] == 'success':
        return VerifyResponse(
            success=True,
            amount=data['data']['amount'] / 100,
            currency=data['data']['currency'],
            email=data['data']['customer']['email'],
        )

    return VerifyResponse(success=False)

Production Checklist

  1. Use httpx connection pooling. Create a single AsyncClient instance and reuse it across requests instead of creating a new one per request.
  2. Add CORS middleware. Use FastAPI's CORSMiddleware to allow requests from your frontend domain.
  3. Set up webhooks. See Handle Paystack Webhooks in FastAPI.
  4. Use HTTPS. Required for callback and webhook URLs in production.
  5. Validate amounts. Look up the price from your database. Never trust client-submitted amounts.

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓FastAPI is async by default. Use httpx for non-blocking HTTP calls to the Paystack API.
  • ✓Pydantic models validate payment input automatically. FastAPI returns 422 for invalid data.
  • ✓Store your Paystack secret key in environment variables. Use pydantic-settings or python-decouple to load them.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents (ZAR/KES/USD). Validate and convert on the server.
  • ✓Always verify the transaction server-side. The redirect callback alone is not proof of payment.
  • ✓FastAPI auto-generates OpenAPI docs for your payment endpoints, which helps frontend developers integrate.

Frequently Asked Questions

Why use httpx instead of requests?
The requests library is synchronous. FastAPI is async. Using requests blocks the event loop. httpx provides an async API (AsyncClient) that works naturally with FastAPI async endpoints.
Can I use the requests library with FastAPI?
Yes, but only in synchronous (non-async) endpoints using def instead of async def. FastAPI runs synchronous endpoints in a thread pool. For best performance, use httpx with async def.
Does FastAPI auto-generate docs for my payment API?
Yes. Visit /docs for Swagger UI or /redoc for ReDoc. FastAPI generates these from your Pydantic models and type annotations. This helps your frontend team understand the payment API without separate documentation.
How do I add authentication to payment endpoints?
Use FastAPI Depends with an authentication dependency. For JWT auth, decode the token in a dependency and inject the current user into your endpoint. Only authenticated users should be able to initialize payments.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Svelte and SvelteKit

Accept Paystack payments in SvelteKit using server endpoints for backend logic and Svelte components for the frontend. This guide covers initializing transactions, inline popup checkout, redirect checkout, and verification in a single full-stack SvelteKit project.

Read more

Handle Paystack Webhooks in Flask

Receive and verify Paystack webhooks in your Flask application. This guide covers accessing request.data for raw bytes, HMAC SHA-512 signature verification, processing charge.success events, and making handlers idempotent.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Paystack Product API for Simple Storefronts

The Paystack Product API lets you create products with names, prices, and descriptions, then generate payment links for each one. For simple storefronts selling a handful of products, this is faster than building a full e-commerce backend. This guide covers creating products, linking them to payment pages, and knowing when to outgrow this approach.

Read more

Paystack Transfer Failed: Reasons and Recovery

Paystack transfers fail for specific, diagnosable reasons. This guide covers every failure reason, the exact webhook payload for each, and a production-ready recovery strategy with code.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.