Add complete FastAPI delivery business backend

- Created customer, driver, and order models with SQLAlchemy
- Implemented CRUD API endpoints for all entities
- Set up SQLite database with Alembic migrations
- Added health check and base URL endpoints
- Configured CORS middleware for all origins
- Updated README with comprehensive documentation
This commit is contained in:
Automated Action 2025-06-27 09:19:00 +00:00
parent a3da62bafc
commit b3827bf6b3
22 changed files with 710 additions and 2 deletions

View File

@ -1,3 +1,84 @@
# FastAPI Application # Delivery Business API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A simple FastAPI backend for managing a delivery business with customers, drivers, and orders.
## Features
- **Customer Management**: Create, read, update, and delete customers
- **Driver Management**: Manage drivers with availability and ratings
- **Order Management**: Handle delivery orders with status tracking
- **SQLite Database**: Lightweight database with Alembic migrations
- **Health Check**: Monitor service health at `/health`
- **Interactive API Docs**: Available at `/docs` and `/redoc`
## Setup and Installation
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run database migrations:
```bash
alembic upgrade head
```
3. Start the application:
```bash
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
```
The API will be available at `http://localhost:8000`
## API Endpoints
### Base
- `GET /` - Service information
- `GET /health` - Health check
- `GET /docs` - Interactive API documentation
- `GET /openapi.json` - OpenAPI schema
### Customers
- `POST /api/v1/customers` - Create customer
- `GET /api/v1/customers` - List customers
- `GET /api/v1/customers/{id}` - Get customer by ID
- `PUT /api/v1/customers/{id}` - Update customer
- `DELETE /api/v1/customers/{id}` - Delete customer
### Drivers
- `POST /api/v1/drivers` - Create driver
- `GET /api/v1/drivers` - List drivers (supports `available_only` filter)
- `GET /api/v1/drivers/{id}` - Get driver by ID
- `PUT /api/v1/drivers/{id}` - Update driver
- `DELETE /api/v1/drivers/{id}` - Delete driver
### Orders
- `POST /api/v1/orders` - Create order
- `GET /api/v1/orders` - List orders (supports `status` filter)
- `GET /api/v1/orders/{id}` - Get order by ID
- `PUT /api/v1/orders/{id}` - Update order
- `PATCH /api/v1/orders/{id}/assign-driver/{driver_id}` - Assign driver to order
- `PATCH /api/v1/orders/{id}/status` - Update order status
- `DELETE /api/v1/orders/{id}` - Delete order
## Database
The application uses SQLite database located at `/app/storage/db/db.sqlite`. Database migrations are managed using Alembic.
## Order Status Flow
Orders progress through the following statuses:
- `PENDING` - Order created, awaiting confirmation
- `CONFIRMED` - Order confirmed, driver assigned
- `PICKED_UP` - Package picked up by driver
- `IN_TRANSIT` - Package in transit
- `DELIVERED` - Package delivered successfully
- `CANCELLED` - Order cancelled
## Development
The application includes:
- CORS middleware configured to allow all origins
- Automatic API documentation generation
- Database relationship management
- Error handling and validation

42
alembic.ini Normal file
View File

@ -0,0 +1,42 @@
[alembic]
script_location = alembic
prepend_sys_path = .
version_path_separator = os
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[post_write_hooks]
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

52
alembic/env.py Normal file
View File

@ -0,0 +1,52 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from app.db.base import Base
from app.models import Customer, Driver, Order
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
alembic/script.py.mako Normal file
View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,66 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2024-01-01 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create customers table
op.create_table('customers',
sa.Column('id', sa.Integer(), primary_key=True, index=True),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False, index=True),
sa.Column('phone', sa.String(length=20), nullable=False),
sa.Column('address', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP')),
sa.Column('updated_at', sa.DateTime(timezone=True), onupdate=sa.text('CURRENT_TIMESTAMP')),
sa.UniqueConstraint('email')
)
# Create drivers table
op.create_table('drivers',
sa.Column('id', sa.Integer(), primary_key=True, index=True),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False, index=True),
sa.Column('phone', sa.String(length=20), nullable=False),
sa.Column('vehicle_type', sa.String(length=50), nullable=False),
sa.Column('vehicle_plate', sa.String(length=20), nullable=False),
sa.Column('is_available', sa.Boolean(), default=True),
sa.Column('rating', sa.Float(), default=5.0),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP')),
sa.Column('updated_at', sa.DateTime(timezone=True), onupdate=sa.text('CURRENT_TIMESTAMP')),
sa.UniqueConstraint('email')
)
# Create orders table
op.create_table('orders',
sa.Column('id', sa.Integer(), primary_key=True, index=True),
sa.Column('customer_id', sa.Integer(), sa.ForeignKey('customers.id'), nullable=False),
sa.Column('driver_id', sa.Integer(), sa.ForeignKey('drivers.id'), nullable=True),
sa.Column('pickup_address', sa.Text(), nullable=False),
sa.Column('delivery_address', sa.Text(), nullable=False),
sa.Column('package_description', sa.Text(), nullable=True),
sa.Column('weight', sa.Float(), nullable=True),
sa.Column('price', sa.Float(), nullable=False),
sa.Column('status', sa.Enum('PENDING', 'CONFIRMED', 'PICKED_UP', 'IN_TRANSIT', 'DELIVERED', 'CANCELLED', name='orderstatus'), default='PENDING'),
sa.Column('notes', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP')),
sa.Column('updated_at', sa.DateTime(timezone=True), onupdate=sa.text('CURRENT_TIMESTAMP'))
)
def downgrade() -> None:
op.drop_table('orders')
op.drop_table('drivers')
op.drop_table('customers')

0
app/__init__.py Normal file
View File

3
app/db/base.py Normal file
View File

@ -0,0 +1,3 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

23
app/db/session.py Normal file
View File

@ -0,0 +1,23 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .base import Base
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

5
app/models/__init__.py Normal file
View File

@ -0,0 +1,5 @@
from .customer import Customer
from .driver import Driver
from .order import Order, OrderStatus
__all__ = ["Customer", "Driver", "Order", "OrderStatus"]

17
app/models/customer.py Normal file
View File

@ -0,0 +1,17 @@
from sqlalchemy import Column, Integer, String, DateTime, Text
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.db.base import Base
class Customer(Base):
__tablename__ = "customers"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), nullable=False)
email = Column(String(100), unique=True, index=True, nullable=False)
phone = Column(String(20), nullable=False)
address = Column(Text, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
orders = relationship("Order", back_populates="customer")

20
app/models/driver.py Normal file
View File

@ -0,0 +1,20 @@
from sqlalchemy import Column, Integer, String, DateTime, Boolean, Float
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.db.base import Base
class Driver(Base):
__tablename__ = "drivers"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(100), nullable=False)
email = Column(String(100), unique=True, index=True, nullable=False)
phone = Column(String(20), nullable=False)
vehicle_type = Column(String(50), nullable=False)
vehicle_plate = Column(String(20), nullable=False)
is_available = Column(Boolean, default=True)
rating = Column(Float, default=5.0)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
orders = relationship("Order", back_populates="driver")

32
app/models/order.py Normal file
View File

@ -0,0 +1,32 @@
from sqlalchemy import Column, Integer, String, DateTime, Float, ForeignKey, Text, Enum
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import enum
from app.db.base import Base
class OrderStatus(enum.Enum):
PENDING = "pending"
CONFIRMED = "confirmed"
PICKED_UP = "picked_up"
IN_TRANSIT = "in_transit"
DELIVERED = "delivered"
CANCELLED = "cancelled"
class Order(Base):
__tablename__ = "orders"
id = Column(Integer, primary_key=True, index=True)
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False)
driver_id = Column(Integer, ForeignKey("drivers.id"), nullable=True)
pickup_address = Column(Text, nullable=False)
delivery_address = Column(Text, nullable=False)
package_description = Column(Text, nullable=True)
weight = Column(Float, nullable=True)
price = Column(Float, nullable=False)
status = Column(Enum(OrderStatus), default=OrderStatus.PENDING)
notes = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
customer = relationship("Customer", back_populates="orders")
driver = relationship("Driver", back_populates="orders")

5
app/routes/__init__.py Normal file
View File

@ -0,0 +1,5 @@
from .customers import router as customers_router
from .drivers import router as drivers_router
from .orders import router as orders_router
__all__ = ["customers_router", "drivers_router", "orders_router"]

52
app/routes/customers.py Normal file
View File

@ -0,0 +1,52 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.customer import Customer
from app.schemas.customer import Customer as CustomerSchema, CustomerCreate, CustomerUpdate
router = APIRouter()
@router.post("/", response_model=CustomerSchema)
def create_customer(customer: CustomerCreate, db: Session = Depends(get_db)):
db_customer = Customer(**customer.dict())
db.add(db_customer)
db.commit()
db.refresh(db_customer)
return db_customer
@router.get("/", response_model=List[CustomerSchema])
def read_customers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
customers = db.query(Customer).offset(skip).limit(limit).all()
return customers
@router.get("/{customer_id}", response_model=CustomerSchema)
def read_customer(customer_id: int, db: Session = Depends(get_db)):
customer = db.query(Customer).filter(Customer.id == customer_id).first()
if customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
return customer
@router.put("/{customer_id}", response_model=CustomerSchema)
def update_customer(customer_id: int, customer: CustomerUpdate, db: Session = Depends(get_db)):
db_customer = db.query(Customer).filter(Customer.id == customer_id).first()
if db_customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
update_data = customer.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_customer, field, value)
db.commit()
db.refresh(db_customer)
return db_customer
@router.delete("/{customer_id}")
def delete_customer(customer_id: int, db: Session = Depends(get_db)):
customer = db.query(Customer).filter(Customer.id == customer_id).first()
if customer is None:
raise HTTPException(status_code=404, detail="Customer not found")
db.delete(customer)
db.commit()
return {"message": "Customer deleted successfully"}

55
app/routes/drivers.py Normal file
View File

@ -0,0 +1,55 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.driver import Driver
from app.schemas.driver import Driver as DriverSchema, DriverCreate, DriverUpdate
router = APIRouter()
@router.post("/", response_model=DriverSchema)
def create_driver(driver: DriverCreate, db: Session = Depends(get_db)):
db_driver = Driver(**driver.dict())
db.add(db_driver)
db.commit()
db.refresh(db_driver)
return db_driver
@router.get("/", response_model=List[DriverSchema])
def read_drivers(skip: int = 0, limit: int = 100, available_only: bool = False, db: Session = Depends(get_db)):
query = db.query(Driver)
if available_only:
query = query.filter(Driver.is_available == True)
drivers = query.offset(skip).limit(limit).all()
return drivers
@router.get("/{driver_id}", response_model=DriverSchema)
def read_driver(driver_id: int, db: Session = Depends(get_db)):
driver = db.query(Driver).filter(Driver.id == driver_id).first()
if driver is None:
raise HTTPException(status_code=404, detail="Driver not found")
return driver
@router.put("/{driver_id}", response_model=DriverSchema)
def update_driver(driver_id: int, driver: DriverUpdate, db: Session = Depends(get_db)):
db_driver = db.query(Driver).filter(Driver.id == driver_id).first()
if db_driver is None:
raise HTTPException(status_code=404, detail="Driver not found")
update_data = driver.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_driver, field, value)
db.commit()
db.refresh(db_driver)
return db_driver
@router.delete("/{driver_id}")
def delete_driver(driver_id: int, db: Session = Depends(get_db)):
driver = db.query(Driver).filter(Driver.id == driver_id).first()
if driver is None:
raise HTTPException(status_code=404, detail="Driver not found")
db.delete(driver)
db.commit()
return {"message": "Driver deleted successfully"}

78
app/routes/orders.py Normal file
View File

@ -0,0 +1,78 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.order import Order, OrderStatus
from app.schemas.order import Order as OrderSchema, OrderCreate, OrderUpdate
router = APIRouter()
@router.post("/", response_model=OrderSchema)
def create_order(order: OrderCreate, db: Session = Depends(get_db)):
db_order = Order(**order.dict())
db.add(db_order)
db.commit()
db.refresh(db_order)
return db_order
@router.get("/", response_model=List[OrderSchema])
def read_orders(skip: int = 0, limit: int = 100, status: OrderStatus = None, db: Session = Depends(get_db)):
query = db.query(Order)
if status:
query = query.filter(Order.status == status)
orders = query.offset(skip).limit(limit).all()
return orders
@router.get("/{order_id}", response_model=OrderSchema)
def read_order(order_id: int, db: Session = Depends(get_db)):
order = db.query(Order).filter(Order.id == order_id).first()
if order is None:
raise HTTPException(status_code=404, detail="Order not found")
return order
@router.put("/{order_id}", response_model=OrderSchema)
def update_order(order_id: int, order: OrderUpdate, db: Session = Depends(get_db)):
db_order = db.query(Order).filter(Order.id == order_id).first()
if db_order is None:
raise HTTPException(status_code=404, detail="Order not found")
update_data = order.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_order, field, value)
db.commit()
db.refresh(db_order)
return db_order
@router.patch("/{order_id}/assign-driver/{driver_id}")
def assign_driver_to_order(order_id: int, driver_id: int, db: Session = Depends(get_db)):
order = db.query(Order).filter(Order.id == order_id).first()
if order is None:
raise HTTPException(status_code=404, detail="Order not found")
order.driver_id = driver_id
order.status = OrderStatus.CONFIRMED
db.commit()
db.refresh(order)
return {"message": "Driver assigned successfully", "order": order}
@router.patch("/{order_id}/status")
def update_order_status(order_id: int, status: OrderStatus, db: Session = Depends(get_db)):
order = db.query(Order).filter(Order.id == order_id).first()
if order is None:
raise HTTPException(status_code=404, detail="Order not found")
order.status = status
db.commit()
db.refresh(order)
return {"message": "Order status updated successfully", "order": order}
@router.delete("/{order_id}")
def delete_order(order_id: int, db: Session = Depends(get_db)):
order = db.query(Order).filter(Order.id == order_id).first()
if order is None:
raise HTTPException(status_code=404, detail="Order not found")
db.delete(order)
db.commit()
return {"message": "Order deleted successfully"}

9
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,9 @@
from .customer import Customer, CustomerCreate, CustomerUpdate
from .driver import Driver, DriverCreate, DriverUpdate
from .order import Order, OrderCreate, OrderUpdate
__all__ = [
"Customer", "CustomerCreate", "CustomerUpdate",
"Driver", "DriverCreate", "DriverUpdate",
"Order", "OrderCreate", "OrderUpdate"
]

26
app/schemas/customer.py Normal file
View File

@ -0,0 +1,26 @@
from pydantic import BaseModel, EmailStr
from datetime import datetime
from typing import Optional
class CustomerBase(BaseModel):
name: str
email: EmailStr
phone: str
address: str
class CustomerCreate(CustomerBase):
pass
class CustomerUpdate(BaseModel):
name: Optional[str] = None
email: Optional[EmailStr] = None
phone: Optional[str] = None
address: Optional[str] = None
class Customer(CustomerBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

32
app/schemas/driver.py Normal file
View File

@ -0,0 +1,32 @@
from pydantic import BaseModel, EmailStr
from datetime import datetime
from typing import Optional
class DriverBase(BaseModel):
name: str
email: EmailStr
phone: str
vehicle_type: str
vehicle_plate: str
is_available: bool = True
rating: float = 5.0
class DriverCreate(DriverBase):
pass
class DriverUpdate(BaseModel):
name: Optional[str] = None
email: Optional[EmailStr] = None
phone: Optional[str] = None
vehicle_type: Optional[str] = None
vehicle_plate: Optional[str] = None
is_available: Optional[bool] = None
rating: Optional[float] = None
class Driver(DriverBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

36
app/schemas/order.py Normal file
View File

@ -0,0 +1,36 @@
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
from app.models.order import OrderStatus
class OrderBase(BaseModel):
customer_id: int
pickup_address: str
delivery_address: str
package_description: Optional[str] = None
weight: Optional[float] = None
price: float
notes: Optional[str] = None
class OrderCreate(OrderBase):
pass
class OrderUpdate(BaseModel):
driver_id: Optional[int] = None
pickup_address: Optional[str] = None
delivery_address: Optional[str] = None
package_description: Optional[str] = None
weight: Optional[float] = None
price: Optional[float] = None
status: Optional[OrderStatus] = None
notes: Optional[str] = None
class Order(OrderBase):
id: int
driver_id: Optional[int] = None
status: OrderStatus
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

43
main.py Normal file
View File

@ -0,0 +1,43 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routes import customers_router, drivers_router, orders_router
from app.db.session import engine
from app.db.base import Base
Base.metadata.create_all(bind=engine)
app = FastAPI(
title="Delivery Business API",
description="A simple API backend for a delivery business",
version="1.0.0",
openapi_url="/openapi.json"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def root():
return {
"title": "Delivery Business API",
"description": "A simple API backend for a delivery business",
"documentation": "/docs",
"health_check": "/health"
}
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "Delivery Business API"}
app.include_router(customers_router, prefix="/api/v1/customers", tags=["customers"])
app.include_router(drivers_router, prefix="/api/v1/drivers", tags=["drivers"])
app.include_router(orders_router, prefix="/api/v1/orders", tags=["orders"])
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi==0.104.1
uvicorn[standard]==0.24.0
sqlalchemy==2.0.23
alembic==1.12.1
python-multipart==0.0.6
pydantic==2.5.0
ruff==0.1.6