A modern, production-ready FastAPI application with PostgreSQL database integration, featuring user authentication, product management, and a React frontend for data visualization.
This application demonstrates best practices in building RESTful APIs with FastAPI and PostgreSQL. It includes user authentication with JWT tokens, database operations with SQLAlchemy ORM (async), and a React-based frontend for displaying top products by category.
- User Authentication: JWT-based authentication with signup, login, and token refresh
- Product Management: CRUD operations for products with category-based analytics
- Database Operations: Async SQLAlchemy ORM with PostgreSQL
- Data Analytics: Query top products by category with revenue calculations
- Fake Data Generation: Built-in data generator using Faker library
- React Frontend: Interactive UI to display product analytics
- Docker Support: Containerized deployment with Docker Compose
- CORS Enabled: Cross-origin resource sharing for frontend integration
fastapi-psql-app/
βββ database/
β βββ session.py # Database connection and session management
βββ models/
β βββ __init__.py
β βββ pydantic_models.py # Pydantic models for request/response validation
β βββ schema.py # SQLAlchemy database models
βββ routes/
β βββ __init__.py
β βββ login.py # Authentication endpoints (signup, login, token)
β βββ populate_database.py # Database population endpoints
β βββ products.py # Product-related endpoints
βββ utils/
β βββ __init__.py
β βββ user_utils.py # JWT token and password utilities
βββ top-products/ # React frontend application
β βββ public/
β βββ src/
β βββ package.json
β βββ README.md
βββ main.py # FastAPI application entry point
βββ settings.py # Configuration management with Pydantic settings
βββ requirements.txt # Python dependencies
βββ dockerfile # Docker configuration for FastAPI app
βββ compose.yaml # Docker Compose configuration
βββ generate_data.py # Script to generate fake product data CSV
βββ fake_product_data.csv # Generated product data
βββ top5_customers_categories.sql # SQL query for customer analytics
- FastAPI: Modern, high-performance web framework
- PostgreSQL: Relational database
- SQLAlchemy: ORM with async support
- Pydantic: Data validation and settings management
- asyncpg: Async PostgreSQL driver
- python-jose: JWT token implementation
- passlib & bcrypt: Password hashing
- Faker: Fake data generation
- Pandas: Data manipulation for CSV operations
- React 18: UI library
- Create React App: Build tooling
- Docker: Containerization
- Docker Compose: Multi-container orchestration
- Uvicorn: ASGI server
- Python 3.10 or higher
- PostgreSQL 12 or higher (or use Docker)
- Node.js 16+ and npm (for frontend)
- Docker and Docker Compose (optional, for containerized deployment)
git clone https://github.com/deepanshu17/fastapi-psql-app.git
cd fastapi-psql-appCreate a .env file in the root directory with the following variables:
# Database Configuration
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=your_database_name
POSTGRES_SERVICE=localhost
POSTGRES_PORT=5432Example .env for local development:
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
POSTGRES_DB=fastapi_db
POSTGRES_SERVICE=localhost
POSTGRES_PORT=5432- Create a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies:
pip install -r requirements.txt- Ensure PostgreSQL is running and the database specified in
.envexists:
# Using psql command-line tool
createdb fastapi_db- Run the FastAPI application:
uvicorn main:app --host 0.0.0.0 --port 8001 --reloadThe API will be available at http://localhost:8001
- Build and run with Docker Compose:
# Create external network (if not exists)
docker network create demo-network
# Build and start the container
docker compose up --buildThe API will be available at http://localhost:8001
- Navigate to the frontend directory:
cd top-products- Install dependencies:
npm install- Start the development server:
npm startThe React app will be available at http://localhost:3000
Once the application is running, you can access:
- Swagger UI:
http://localhost:8001/docs - ReDoc:
http://localhost:8001/redoc
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| POST | /signup |
Create new user account | No |
| POST | /login |
Login with username/password | No |
| POST | /token |
OAuth2 token endpoint (for Swagger UI) | No |
| GET | /users/me |
Get current user info | Yes |
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| GET | /products/top-product |
Get top product per category with revenue | No |
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| PUT | /database/ |
Populate DB with fake relational data | No |
| PUT | /database/custom |
Populate DB with CSV product data | No |
id: Integer (Primary Key)username: String (Unique)hashed_password: String
customer_id: UUID (Primary Key)customer_name: Stringemail: Stringsignup_date: Date
product_id: UUID (Primary Key)product_name: Stringcategory: String
product_id: Integer (Primary Key)product_name: Stringcategory: Stringprice: Floatquantity_sold: Integerrating: Floatreview_count: Integer
order_id: UUID (Primary Key)customer_id: UUIDorder_date: Datetotal_amount: Decimal
order_item_id: UUID (Primary Key)order_id: UUIDproduct_id: UUIDquantity: Integerprice_per_unit: Decimal
To generate a CSV file with fake product data:
python generate_data.pyThis creates fake_product_data.csv with 50,000 product records across 6 categories.
Option 1: Populate with relational data (customers, orders, products)
curl -X PUT "http://localhost:8001/database/" \
-H "Content-Type: application/json" \
-d '{"customer_count": 500, "product_count": 100, "order_count": 1000}'Option 2: Populate with custom product data from CSV
curl -X PUT "http://localhost:8001/database/custom" \
-H "Content-Type: application/json" \
-d '{}'uvicorn main:app --reload --host 0.0.0.0 --port 8001docker build -t fastapi_app_image .docker run -p 8001:8001 --env-file .env fastapi_app_image# Start services
docker compose up -d
# View logs
docker compose logs -f
# Stop services
docker compose down
# Rebuild and restart
docker compose up --build- The application uses JWT tokens for authentication
- Passwords are hashed using bcrypt
- Important: Change the
SECRET_KEYinutils/user_utils.pyfor production - Update CORS settings in
main.pyto restrict origins in production - Never commit
.envfiles with sensitive credentials
The API can be tested using:
- Swagger UI:
http://localhost:8001/docs(interactive API testing) - Postman: Import endpoints from the Swagger JSON
- curl: Command-line HTTP requests (examples above)
The repository includes a SQL file top5_customers_categories.sql that demonstrates:
- Finding top 5 customers by spending in the last year
- Identifying their most purchased product category
The React application (top-products/) provides:
- Visual display of top products by category
- Revenue information per category
- Responsive UI design
- 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 available for educational and demonstration purposes.
Deepanshu
- GitHub: @deepanshu17
- FastAPI framework for excellent documentation and developer experience
- SQLAlchemy for powerful ORM capabilities
- Faker library for test data generation