E-Commerce API
A FastAPI-based RESTful API for an e-commerce application with user authentication, product catalog, shopping cart, order processing, and payment processing.
Features
- User authentication with JWT
- Product catalog with categories
- Shopping cart functionality
- Order management
- Mock payment processing
- Search and filtering products
- Admin and regular user roles
Technology Stack
- Framework: FastAPI
- Database: SQLite
- ORM: SQLAlchemy
- Migration Tool: Alembic
- Authentication: JWT with password hashing
Project Structure
ecommerce-api/
├── app/
│ ├── api/
│ │ ├── deps.py
│ │ └── v1/
│ │ ├── api.py
│ │ └── endpoints/
│ │ ├── auth.py
│ │ ├── cart.py
│ │ ├── categories.py
│ │ ├── health.py
│ │ ├── orders.py
│ │ ├── payments.py
│ │ ├── products.py
│ │ └── users.py
│ ├── core/
│ │ ├── config.py
│ │ └── security.py
│ ├── db/
│ │ └── session.py
│ ├── models/
│ │ ├── base.py
│ │ ├── cart.py
│ │ ├── order.py
│ │ ├── product.py
│ │ └── user.py
│ ├── schemas/
│ │ ├── cart.py
│ │ ├── order.py
│ │ ├── product.py
│ │ ├── token.py
│ │ └── user.py
│ └── services/
├── migrations/
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
│ └── 0001_create_tables.py
├── storage/
│ └── db/
├── alembic.ini
├── main.py
└── requirements.txt
Setup and Installation
1. Clone the repository
git clone https://github.com/your-username/ecommerce-api.git
cd ecommerce-api
2. Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
3. Install dependencies
pip install -r requirements.txt
4. Set up environment variables
Create a .env
file in the root directory:
JWT_SECRET_KEY=your_secret_key_here
5. Initialize the database
alembic upgrade head
6. Run the application
uvicorn main:app --reload
The API will be available at http://localhost:8000.
API Documentation
Once the application is running, you can access the API documentation at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
API Endpoints
Authentication
POST /api/v1/auth/register
- Register a new user with email and passwordPOST /api/v1/auth/login
- Login with email (provided in the username field) and password to get access token
Users
GET /api/v1/users/me
- Get current user informationPUT /api/v1/users/me
- Update current user informationGET /api/v1/users/{user_id}
- Get user by ID (admin only)GET /api/v1/users/
- List all users (admin only)
Categories
GET /api/v1/categories/
- List all categoriesPOST /api/v1/categories/
- Create a new category (admin only)GET /api/v1/categories/{category_id}
- Get category by IDPUT /api/v1/categories/{category_id}
- Update a category (admin only)DELETE /api/v1/categories/{category_id}
- Delete a category (admin only)
Products
GET /api/v1/products/
- List all products (with filtering options)POST /api/v1/products/
- Create a new product (admin only)GET /api/v1/products/{product_id}
- Get product by IDPUT /api/v1/products/{product_id}
- Update a product (admin only)DELETE /api/v1/products/{product_id}
- Delete a product (admin only)
Cart
GET /api/v1/cart/
- Get user's cartPOST /api/v1/cart/items
- Add item to cartPUT /api/v1/cart/items/{item_id}
- Update cart item quantityDELETE /api/v1/cart/items/{item_id}
- Remove item from cartDELETE /api/v1/cart/
- Clear cart
Orders
GET /api/v1/orders/
- List user's orders (admin can see all)POST /api/v1/orders/
- Create a new order from cartGET /api/v1/orders/{order_id}
- Get order by IDPUT /api/v1/orders/{order_id}
- Update order (limited for regular users)DELETE /api/v1/orders/{order_id}
- Cancel order
Payments
POST /api/v1/payments/
- Process payment for an order
Health Check
GET /health
- Application health checkGET /api/v1/health/
- Detailed health check
Environment Variables
Variable | Description | Default |
---|---|---|
JWT_SECRET_KEY | Secret key for JWT token generation | supersecretkey |
JWT_ALGORITHM | Algorithm used for JWT | HS256 |
ACCESS_TOKEN_EXPIRE_MINUTES | Token expiration time in minutes | 30 |
Database
The application uses SQLite as the database. The database file is created at /app/storage/db/db.sqlite
.
CORS Configuration
The API has robust CORS (Cross-Origin Resource Sharing) enabled with the following configuration:
-
Allowed origins:
- http://localhost
- http://localhost:3000
- http://127.0.0.1
- http://127.0.0.1:3000
- https://v0-ecommerce-app-build-swart.vercel.app
- https://*.vercel.app (for preview deployments)
-
- (wildcard for development)
-
Allowed methods: GET, POST, PUT, DELETE, OPTIONS, PATCH
-
Allowed headers:
- Authorization
- Content-Type
- Accept
- Accept-Language
- Content-Language
- Content-Length
- Origin
- X-Requested-With
- X-CSRF-Token
- Access-Control-Allow-Origin
- Access-Control-Allow-Credentials
- X-HTTP-Method-Override
-
Exposed headers: Content-Length, Content-Type, Authorization
-
Credentials support: Enabled (supports JWT authentication)
-
Max age for preflight requests: 3600 seconds (1 hour)
Custom CORS Handling
This application implements a low-level ASGI CORS middleware that properly handles preflight OPTIONS requests for all endpoints, including authentication routes. The implementation includes:
- Low-level ASGI middleware that directly handles HTTP requests before FastAPI routing
- Special handling for OPTIONS preflight requests for all routes
- Explicit support for POST requests with JSON content-type
- Full support for Authorization headers for authenticated endpoints
- Dedicated OPTIONS route handlers for critical endpoints like authentication
The CORS system is implemented at multiple levels to ensure maximum compatibility:
- ASGI Middleware: Intercepts all requests at the ASGI protocol level before FastAPI processing
- Dedicated OPTIONS Handlers: Specific route handlers for authentication endpoints
- Response Header Injection: Adds proper CORS headers to all responses
Critical Endpoints with Special CORS Support
The API includes dedicated OPTIONS handlers for these critical endpoints:
OPTIONS /api/v1/auth/register
- Register endpoint preflight supportOPTIONS /api/v1/auth/login
- Login endpoint preflight supportOPTIONS /api/v1/users/me
- User profile endpoint preflight supportOPTIONS /api/v1/cors-test
- Test preflight requestsPOST /api/v1/cors-test
- Test POST requests with JSON body