A comprehensive purchase data management system built with FastAPI and GraphQL, featuring robust schema design for e-commerce applications.
- Comprehensive Purchase Tracking - Complete order management with multiple status tracking
- Customer Management - Detailed customer profiles with address and preference management
- Product Catalog - Full product management with inventory tracking
- Financial Tracking - Multi-currency support, tax, shipping, and discount management
- Marketing Analytics - UTM tracking, source attribution, and campaign analytics
- Fraud Prevention - Risk scoring and fraud detection capabilities
- GraphQL API - Flexible, efficient data querying with GraphQL
- Historical Data - Product snapshots preserve pricing and product info at purchase time
- Installation
- Quick Start
- Schema Overview
- API Documentation
- Database Setup
- GraphQL Examples
- Environment Configuration
- Development
- Contributing
- Python 3.8+
- PostgreSQL 12+
- pip or poetry
# Clone the repository
git clone <repository-url>
cd fastapi-graphql
# Install dependencies
pip install -r requirements.txt
# Or using poetry
poetry installCreate a .env file in the root directory:
DATABASE_URL=postgresql://username:password@localhost:5432/fastapi_graphql
DEBUG=True
SECRET_KEY=your-secret-key-here# Create PostgreSQL database
createdb fastapi_graphql
# Run the application (this will create tables automatically)
python -m app.main# Using uvicorn directly
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# Or using Python
python -m app.main- API Root: http://localhost:8000
- GraphQL Playground: http://localhost:8000/graphql
- Health Check: http://localhost:8000/health
The system consists of four main models:
| Model | Description | Key Features |
|---|---|---|
| Customer | Customer profiles and information | Address management, marketing preferences |
| Product | Product catalog and inventory | SKU tracking, pricing, inventory management |
| Purchase | Main order/purchase records | Status tracking, payments, shipping |
| PurchaseItem | Individual line items within orders | Quantity, pricing, fulfillment tracking |
Customer (1) ←→ (Many) Purchase
Product (1) ←→ (Many) PurchaseItem
Purchase (1) ←→ (Many) PurchaseItem
Endpoint: /graphql
# Get all customers
customers {
id
firstName
lastName
email
isActive
}
# Get specific customer
customer(id: 1) {
id
firstName
lastName
email
purchases {
orderNumber
totalAmount
status
}
}
# Get all products
products {
id
name
sku
price
stockQuantity
}
# Get all purchases
purchases {
id
orderNumber
totalAmount
status
customer {
firstName
lastName
}
items {
quantity
unitPrice
product {
name
}
}
}# Create a new customer
mutation {
createCustomer(
firstName: "John"
lastName: "Doe"
email: "[email protected]"
phone: "+1234567890"
) {
customer {
id
firstName
lastName
email
}
}
}
# Create a new product
mutation {
createProduct(
name: "Premium Widget"
sku: "WIDGET-001"
price: 29.99
description: "A high-quality widget"
) {
product {
id
name
sku
price
}
}
}-
Install PostgreSQL:
# macOS brew install postgresql # Ubuntu sudo apt-get install postgresql postgresql-contrib
-
Create Database:
createdb fastapi_graphql
-
Update Connection String:
DATABASE_URL=postgresql://username:password@localhost:5432/fastapi_graphql
For production environments, consider using Alembic for migrations:
# Initialize Alembic
alembic init alembic
# Create migration
alembic revision --autogenerate -m "Initial migration"
# Apply migration
alembic upgrade headquery GetPurchaseDetails {
purchases {
id
orderNumber
purchaseDate
status
totalAmount
currency
customer {
firstName
lastName
email
}
items {
quantity
unitPrice
totalPrice
product {
name
sku
category
}
}
# Payment information
paymentStatus
paymentMethod
# Shipping information
shippingCity
shippingCountry
trackingNumber
}
}query GetPendingOrders {
purchases(status: "PENDING") {
orderNumber
totalAmount
customer {
email
}
}
}Create a .env file with the following variables:
# Database Configuration
DATABASE_URL=postgresql://username:password@localhost:5432/fastapi_graphql
# Application Configuration
APP_NAME=FastAPI GraphQL Purchase System
APP_VERSION=1.0.0
DEBUG=True
# Security
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# CORS Settings
ALLOWED_ORIGINS=["http://localhost:3000", "http://localhost:8000"]
# Payment Gateway (Example)
STRIPE_SECRET_KEY=sk_test_your_stripe_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_key
# Email Configuration (Optional)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=[email protected]
SMTP_PASSWORD=your-app-passwordfastapi-graphql/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI application
│ ├── schema.py # GraphQL schema
│ └── models/
│ ├── __init__.py
│ ├── base.py # Database configuration
│ ├── customer.py # Customer model
│ ├── product.py # Product model
│ └── purchase.py # Purchase models
├── requirements.txt # Dependencies
├── README.md # This file
├── PURCHASE_SCHEMA_DOCUMENTATION.md # Detailed schema docs
└── .env.example # Environment template
# Install test dependencies
pip install pytest pytest-asyncio
# Run tests
pytest# Install formatting tools
pip install black isort
# Format code
black .
isort .The schema includes strategic indexes on:
- Customer email (unique)
- Product SKU (unique)
- Purchase order_number (unique)
- Purchase status
- Foreign key relationships
- Use field selection to only fetch required data
- Implement DataLoader for N+1 query prevention
- Consider query complexity limits for production
- Risk Scoring: Built-in fraud detection with risk scoring
- Payment Security: Secure payment gateway integration support
- Data Validation: Comprehensive input validation with Pydantic
- CORS Configuration: Configurable CORS settings
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]DATABASE_URL=postgresql://user:pass@db:5432/production_db
DEBUG=False
SECRET_KEY=production-secret-key
ALLOWED_ORIGINS=["https://yourdomain.com"]- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For support, email [email protected] or create an issue in this repository.
Built with ❤️ using FastAPI and GraphQL