Skip to content

KrushnaSonawane24/FastAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI E-Commerce API

A robust and feature-rich RESTful API for e-commerce product management built with FastAPI, featuring advanced data validation, filtering capabilities, and an interactive Streamlit admin dashboard.

πŸš€ Features

Backend API (FastAPI)

  • CRUD Operations: Complete product management (Create, Read, Update, Delete)
  • Advanced Filtering: Filter products by name, category, price, with sorting and pagination
  • Data Validation: Robust Pydantic models with custom validators
  • Business Logic Validation:
    • SKU format validation
    • Stock and availability rules
    • Seller email domain restrictions
    • Rating and discount validation
  • Computed Fields: Automatic calculation of final price and product volume
  • HTTP Middleware: Request/response lifecycle logging
  • Dependency Injection: Clean architecture with dependency management
  • Environment Variables: Configuration via .env file

Frontend Dashboard (Streamlit)

  • Interactive UI: Beautiful admin dashboard for product management
  • Product Catalog: Browse, search, and filter products
  • Add Products: User-friendly form to add new products
  • Update/Delete: Manage existing products with ease
  • Real-time API Integration: Direct communication with FastAPI backend

Data Model Features

  • UUID-based product identification
  • SKU validation with custom format requirements
  • Multi-dimensional product attributes (dimensions, ratings, tags)
  • Seller information with email domain validation
  • Image URL support
  • Timestamp tracking (created_at)

πŸ“‹ Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)

πŸ› οΈ Installation

  1. Clone the repository

    git clone <your-repository-url>
    cd fastapi_ecomerce
  2. Create a virtual environment

    python -m venv venv
  3. Activate the virtual environment

    • Windows:
      venv\Scripts\activate
    • macOS/Linux:
      source venv/bin/activate
  4. Install dependencies

    pip install -r requirements.txt
    pip install streamlit  # For the frontend dashboard
  5. Set up environment variables

    Create a .env file in the app/ directory:

    base_url=./app/data/products.json
  6. Create the data directory

    mkdir -p app/data
  7. Initialize the products database

    Create an empty products.json file:

    echo [] > app/data/products.json

πŸš€ Running the Application

Start the FastAPI Backend

uvicorn app.mainn:app --reload

The API will be available at: http://127.0.0.1:8000

API Documentation (auto-generated by FastAPI):

  • Swagger UI: http://127.0.0.1:8000/docs
  • ReDoc: http://127.0.0.1:8000/redoc

Start the Streamlit Frontend

In a new terminal (with the backend running):

streamlit run streamlit_app.py

The dashboard will open in your browser at: http://localhost:8501

πŸ“š API Endpoints

Health Check

GET /

Returns a welcome message with configuration details.

Get All Products (with Filtering)

GET /products?name={name}&category={category}&price={max_price}&order={asc|desc}&limit={limit}

Query Parameters:

  • name (optional): Filter by product name (case-insensitive)
  • category (optional): Filter by category (laptops, mobiles, accessories, electronics)
  • price (optional): Maximum price filter
  • order (optional): Sort order - "asc" or "desc" (default: "asc")
  • limit (optional): Number of items to return (1-100, default: 10)

Example:

curl "http://127.0.0.1:8000/products?category=laptops&price=50000&order=desc&limit=5"

Get Product by ID

GET /products/{product_id}

Example:

curl "http://127.0.0.1:8000/products/123e4567-e89b-12d3-a456-426614174000"

Create Product

POST /products
Content-Type: application/json

Request Body Example:

{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "sku": "REAL-135GB-001",
  "name": "Realme 9 Pro 5G",
  "description": "6GB RAM, 128GB Storage, Midnight Black",
  "category": "mobiles",
  "brand": "Realme",
  "price": 17999.0,
  "currency": "INR",
  "discount_percent": 15,
  "stock": 50,
  "is_active": true,
  "rating": 4.5,
  "tags": ["5G", "Android", "Smartphone"],
  "image_urls": ["https://example.com/image1.jpg"],
  "dimensions_cm": {
    "length": 16.4,
    "width": 7.59,
    "height": 0.82
  },
  "seller": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Realme Official Store",
    "email": "support@mistore.in",
    "website": "https://www.realme.com"
  },
  "created_at": "2026-01-16T12:00:00Z"
}

Update Product

PATCH /product/{product_id}
Content-Type: application/json

Request Body Example (partial update):

{
  "price": 16999.0,
  "stock": 45,
  "discount_percent": 20
}

Delete Product

DELETE /products/{product_id}

πŸ—οΈ Project Structure

fastapi_ecomerce/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ mainn.py              # Main FastAPI application & routes
β”‚   β”œβ”€β”€ .env                  # Environment variables
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   └── products.json     # JSON database
β”‚   β”œβ”€β”€ schema/
β”‚   β”‚   └── product.py        # Pydantic models for validation
β”‚   └── service/
β”‚       └── products.py       # Business logic & data operations
β”œβ”€β”€ scripts/
β”œβ”€β”€ streamlit_app.py          # Streamlit admin dashboard
β”œβ”€β”€ requirements.txt          # Python dependencies
β”œβ”€β”€ LICENSE                   # MIT License
β”œβ”€β”€ .gitignore
└── README.md                 # This file

πŸ”§ Key Components

1. Pydantic Models (app/schema/product.py)

  • Product: Main product model with comprehensive validation
  • DimensionCm: Product dimensions validation
  • Seller: Seller information with email domain validation
  • productUpdate: Model for partial updates
  • Custom validators for SKU format, business rules, and seller emails

2. Service Layer (app/service/products.py)

  • get_all_products(): Retrieve all products
  • add_product(): Create a new product with SKU uniqueness check
  • remove_product(): Delete a product by ID
  • change_product(): Update product with partial data

3. Main API (app/mainn.py)

  • FastAPI application setup
  • HTTP middleware for request logging
  • Dependency injection examples
  • Route handlers for all CRUD operations
  • Query parameter validation and filtering logic

4. Streamlit Dashboard (streamlit_app.py)

  • Home page with overview
  • Product catalog with search and filters
  • Add new product form
  • Update and delete operations

βœ… Validation Rules

SKU Format

  • Must contain a hyphen (-)
  • Must end with exactly 3 digits (e.g., -001)
  • Example: REAL-135GB-001

Business Rules

  • If stock is 0, is_active must be false
  • Products with discount_percent > 0 must have rating > 0

Seller Email Domains

Only these domains are allowed:

  • lenovostore.in
  • samsungindia.in
  • mistore.in
  • asusexclusive.in
  • hpworld.in
  • oneplusstore.in

Product Constraints

  • Name: 6-80 characters
  • Description: Max 200 characters
  • Price: Must be >= 0
  • Discount: 0-90%
  • Rating: 0-5 stars
  • Stock: Must be >= 0
  • Tags: Maximum 10 tags

πŸ§ͺ Testing the API

Using cURL

Get all products:

curl http://127.0.0.1:8000/products

Filter by category:

curl "http://127.0.0.1:8000/products?category=mobiles&limit=5"

Get product by ID:

curl http://127.0.0.1:8000/products/{product_id}

Using Swagger UI

  1. Start the FastAPI server
  2. Open http://127.0.0.1:8000/docs in your browser
  3. Try out the endpoints interactively

πŸ”’ Environment Variables

Create an app/.env file with:

base_url=./app/data/products.json

πŸ“¦ Dependencies

  • fastapi: Modern web framework for building APIs
  • uvicorn: ASGI server for running FastAPI
  • python-dotenv: Load environment variables from .env
  • pydantic: Data validation using Python type annotations
  • streamlit: Frontend dashboard framework

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ‘¨β€πŸ’» Author

Krushna Sonawane

πŸ™ Acknowledgments

  • FastAPI documentation and community
  • Pydantic for excellent data validation
  • Streamlit for the beautiful dashboard framework

πŸ› Known Issues & Future Enhancements

Planned Features

  • Database integration (PostgreSQL/MongoDB)
  • User authentication and authorization
  • Image upload functionality
  • Order management system
  • Payment gateway integration
  • Email notifications
  • Advanced analytics dashboard
  • API rate limiting
  • Caching layer (Redis)
  • Unit and integration tests

πŸ“§ Support

For issues, questions, or suggestions, please open an issue in the repository.


Happy Coding! πŸš€

About

Production-style FastAPI REST API with CRUD operations, advanced Pydantic validation, and modular project structure.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages