Implement Rental Services API with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-06-02 12:04:09 +00:00
parent f255b82eb3
commit 8d53ada264
33 changed files with 1245 additions and 2 deletions

117
README.md
View File

@ -1,3 +1,116 @@
# FastAPI Application
# Rental Services API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
This is a FastAPI application for managing rental services. It provides endpoints for managing rental items, categories, customers, and rental records.
## Features
- Rental items management (with categories)
- Customer management
- Rental records tracking
- SQLite database with SQLAlchemy ORM
- Alembic for database migrations
- OpenAPI documentation
## API Endpoints
### Health Check
- GET `/health` - Check API health
### Categories
- GET `/api/v1/rentals/categories/` - List all categories
- GET `/api/v1/rentals/categories/{category_id}` - Get category by ID
### Rental Items
- GET `/api/v1/rentals/items/` - List all rental items
- Query params:
- `category_id` - Filter by category
- `available_only` - Filter by availability
- GET `/api/v1/rentals/items/{item_id}` - Get rental item by ID
### Customers
- GET `/api/v1/rentals/customers/` - List all customers
- GET `/api/v1/rentals/customers/{customer_id}` - Get customer by ID
- GET `/api/v1/rentals/customers/email/{email}` - Get customer by email
### Rental Records
- GET `/api/v1/rentals/records/` - List all rental records
- Query params:
- `customer_id` - Filter by customer
- `item_id` - Filter by rental item
- `active_only` - Filter active rentals only
- GET `/api/v1/rentals/records/{record_id}` - Get rental record by ID
## Project Structure
```
├── app/
│ ├── api/
│ │ └── v1/
│ │ ├── endpoints/
│ │ │ └── rentals.py # API endpoints
│ │ └── api.py # API router
│ ├── core/
│ │ └── config.py # Application configuration
│ ├── crud/
│ │ ├── base.py # Base CRUD operations
│ │ ├── crud_category.py # Category CRUD operations
│ │ ├── crud_customer.py # Customer CRUD operations
│ │ ├── crud_rental_item.py # Rental item CRUD operations
│ │ └── crud_rental_record.py # Rental record CRUD operations
│ ├── db/
│ │ └── session.py # Database session
│ ├── models/
│ │ ├── base.py # Base model
│ │ └── rental.py # Database models
│ └── schemas/
│ ├── category.py # Category schemas
│ ├── customer.py # Customer schemas
│ ├── rental_item.py # Rental item schemas
│ └── rental_record.py # Rental record schemas
├── migrations/ # Alembic migrations
│ ├── versions/
│ │ └── 001_initial_schema.py # Initial database schema
│ ├── env.py # Migration environment
│ └── script.py.mako # Migration script template
├── alembic.ini # Alembic configuration
├── main.py # Application entry point
└── requirements.txt # Python dependencies
```
## Setup and Running
1. Install dependencies:
```
pip install -r requirements.txt
```
2. Run database migrations:
```
alembic upgrade head
```
3. Start the API server:
```
uvicorn main:app --reload
```
4. Access the API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## Environment Variables
The application uses environment variables for configuration. Create a `.env` file in the root directory with the following variables:
```
PROJECT_NAME=Rental Services API
API_V1_STR=/api/v1
```
## Database
The application uses SQLite as the database. The database file is stored at `/app/storage/db/db.sqlite`. Make sure the directory exists or is created at runtime.
## License
This project is licensed under the MIT License.

97
alembic.ini Normal file
View File

@ -0,0 +1,97 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# SQLite URL example
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
# [post_write_hooks]
# hooks = black, blacken_docs
# black.type = console_scripts
# black.entrypoint = black
# blacken_docs.type = console_scripts
# blacken_docs.entrypoint = blacken_docs
[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

0
app/__init__.py Normal file
View File

0
app/api/__init__.py Normal file
View File

0
app/api/v1/__init__.py Normal file
View File

6
app/api/v1/api.py Normal file
View File

@ -0,0 +1,6 @@
from fastapi import APIRouter
from app.api.v1.endpoints import rentals
api_router = APIRouter(prefix="/api/v1")
api_router.include_router(rentals.router, prefix="/rentals", tags=["rentals"])

View File

View File

@ -0,0 +1,159 @@
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import crud, schemas
from app.db.session import get_db
router = APIRouter()
@router.get("/categories/", response_model=List[schemas.Category])
def read_categories(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve all categories.
"""
categories = crud.category.get_multi(db, skip=skip, limit=limit)
return categories
@router.get("/categories/{category_id}", response_model=schemas.Category)
def read_category(
*,
db: Session = Depends(get_db),
category_id: int,
) -> Any:
"""
Get category by ID.
"""
category = crud.category.get(db, id=category_id)
if not category:
raise HTTPException(status_code=404, detail="Category not found")
return category
@router.get("/items/", response_model=List[schemas.RentalItem])
def read_rental_items(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
category_id: int = None,
available_only: bool = False,
) -> Any:
"""
Retrieve rental items with optional filtering.
"""
if category_id:
items = crud.rental_item.get_by_category(
db, category_id=category_id, skip=skip, limit=limit
)
elif available_only:
items = crud.rental_item.get_available(db, skip=skip, limit=limit)
else:
items = crud.rental_item.get_multi(db, skip=skip, limit=limit)
return items
@router.get("/items/{item_id}", response_model=schemas.RentalItem)
def read_rental_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Get rental item by ID.
"""
item = crud.rental_item.get(db, id=item_id)
if not item:
raise HTTPException(status_code=404, detail="Rental item not found")
return item
@router.get("/customers/", response_model=List[schemas.Customer])
def read_customers(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve all customers.
"""
customers = crud.customer.get_multi(db, skip=skip, limit=limit)
return customers
@router.get("/customers/{customer_id}", response_model=schemas.Customer)
def read_customer(
*,
db: Session = Depends(get_db),
customer_id: int,
) -> Any:
"""
Get customer by ID.
"""
customer = crud.customer.get(db, id=customer_id)
if not customer:
raise HTTPException(status_code=404, detail="Customer not found")
return customer
@router.get("/customers/email/{email}", response_model=schemas.Customer)
def read_customer_by_email(
*,
db: Session = Depends(get_db),
email: str,
) -> Any:
"""
Get customer by email.
"""
customer = crud.customer.get_by_email(db, email=email)
if not customer:
raise HTTPException(status_code=404, detail="Customer not found")
return customer
@router.get("/records/", response_model=List[schemas.RentalRecord])
def read_rental_records(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
customer_id: int = None,
item_id: int = None,
active_only: bool = False,
) -> Any:
"""
Retrieve rental records with optional filtering.
"""
if customer_id:
records = crud.rental_record.get_by_customer(
db, customer_id=customer_id, skip=skip, limit=limit
)
elif item_id:
records = crud.rental_record.get_by_item(
db, item_id=item_id, skip=skip, limit=limit
)
elif active_only:
records = crud.rental_record.get_active(db, skip=skip, limit=limit)
else:
records = crud.rental_record.get_multi(db, skip=skip, limit=limit)
return records
@router.get("/records/{record_id}", response_model=schemas.RentalRecord)
def read_rental_record(
*,
db: Session = Depends(get_db),
record_id: int,
) -> Any:
"""
Get rental record by ID.
"""
record = crud.rental_record.get(db, id=record_id)
if not record:
raise HTTPException(status_code=404, detail="Rental record not found")
return record

0
app/core/__init__.py Normal file
View File

34
app/core/config.py Normal file
View File

@ -0,0 +1,34 @@
from pathlib import Path
from typing import List
from pydantic import AnyHttpUrl, field_validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""Application settings."""
PROJECT_NAME: str = "Rental Services API"
API_V1_STR: str = "/api/v1"
# Database
DB_DIR: Path = Path("/app") / "storage" / "db"
# CORS
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
@classmethod
def assemble_cors_origins(cls, v) -> List[str]:
"""Parse CORS origins from env variables."""
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()

4
app/crud/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from app.crud.crud_category import category
from app.crud.crud_customer import customer
from app.crud.crud_rental_item import rental_item
from app.crud.crud_rental_record import rental_record

80
app/crud/base.py Normal file
View File

@ -0,0 +1,80 @@
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.models.base import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
"""
CRUD base class with default methods to Create, Read, Update, Delete (CRUD).
"""
def __init__(self, model: Type[ModelType]):
"""
Initialize CRUD instance with the specified SQLAlchemy model.
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
"""
Get a model instance by id.
"""
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
"""
Get multiple model instances.
"""
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
"""
Create a new model instance.
"""
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
"""
Update a model instance.
"""
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
"""
Delete a model instance.
"""
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

22
app/crud/crud_category.py Normal file
View File

@ -0,0 +1,22 @@
from typing import Optional
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.rental import Category
from app.schemas.category import CategoryCreate, CategoryUpdate
class CRUDCategory(CRUDBase[Category, CategoryCreate, CategoryUpdate]):
"""
CRUD operations for Category model.
"""
def get_by_name(self, db: Session, *, name: str) -> Optional[Category]:
"""
Get a category by name.
"""
return db.query(Category).filter(Category.name == name).first()
category = CRUDCategory(Category)

35
app/crud/crud_customer.py Normal file
View File

@ -0,0 +1,35 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.rental import Customer
from app.schemas.customer import CustomerCreate, CustomerUpdate
class CRUDCustomer(CRUDBase[Customer, CustomerCreate, CustomerUpdate]):
"""
CRUD operations for Customer model.
"""
def get_by_email(self, db: Session, *, email: str) -> Optional[Customer]:
"""
Get a customer by email.
"""
return db.query(Customer).filter(Customer.email == email).first()
def get_by_name(
self, db: Session, *, first_name: str, last_name: str,
skip: int = 0, limit: int = 100
) -> List[Customer]:
"""
Get customers by first and last name.
"""
return db.query(Customer)\
.filter(Customer.first_name == first_name, Customer.last_name == last_name)\
.offset(skip)\
.limit(limit)\
.all()
customer = CRUDCustomer(Customer)

View File

@ -0,0 +1,46 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.rental import RentalItem
from app.schemas.rental_item import RentalItemCreate, RentalItemUpdate
class CRUDRentalItem(CRUDBase[RentalItem, RentalItemCreate, RentalItemUpdate]):
"""
CRUD operations for RentalItem model.
"""
def get_by_name(self, db: Session, *, name: str) -> Optional[RentalItem]:
"""
Get a rental item by name.
"""
return db.query(RentalItem).filter(RentalItem.name == name).first()
def get_by_category(
self, db: Session, *, category_id: int, skip: int = 0, limit: int = 100
) -> List[RentalItem]:
"""
Get all rental items by category_id.
"""
return db.query(RentalItem)\
.filter(RentalItem.category_id == category_id)\
.offset(skip)\
.limit(limit)\
.all()
def get_available(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[RentalItem]:
"""
Get all available rental items.
"""
return db.query(RentalItem)\
.filter(RentalItem.is_available)\
.offset(skip)\
.limit(limit)\
.all()
rental_item = CRUDRentalItem(RentalItem)

View File

@ -0,0 +1,69 @@
from datetime import date
from typing import List
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.rental import RentalRecord
from app.schemas.rental_record import RentalRecordCreate, RentalRecordUpdate
class CRUDRentalRecord(CRUDBase[RentalRecord, RentalRecordCreate, RentalRecordUpdate]):
"""
CRUD operations for RentalRecord model.
"""
def get_by_customer(
self, db: Session, *, customer_id: int, skip: int = 0, limit: int = 100
) -> List[RentalRecord]:
"""
Get all rental records for a customer.
"""
return db.query(RentalRecord)\
.filter(RentalRecord.customer_id == customer_id)\
.offset(skip)\
.limit(limit)\
.all()
def get_by_item(
self, db: Session, *, item_id: int, skip: int = 0, limit: int = 100
) -> List[RentalRecord]:
"""
Get all rental records for an item.
"""
return db.query(RentalRecord)\
.filter(RentalRecord.item_id == item_id)\
.offset(skip)\
.limit(limit)\
.all()
def get_active(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[RentalRecord]:
"""
Get all active rental records (not yet returned).
"""
return db.query(RentalRecord)\
.filter(RentalRecord.actual_return_date is None)\
.offset(skip)\
.limit(limit)\
.all()
def get_by_date_range(
self, db: Session, *, start_date: date, end_date: date,
skip: int = 0, limit: int = 100
) -> List[RentalRecord]:
"""
Get all rental records within a date range.
"""
return db.query(RentalRecord)\
.filter(
RentalRecord.rental_date >= start_date,
RentalRecord.return_date <= end_date
)\
.offset(skip)\
.limit(limit)\
.all()
rental_record = CRUDRentalRecord(RentalRecord)

0
app/db/__init__.py Normal file
View File

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

@ -0,0 +1,27 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Create the database directory if it doesn't exist
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{settings.DB_DIR}/db.sqlite"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1,2 @@
from app.models.base import Base
from app.models.rental import Category, Customer, RentalItem, RentalRecord

24
app/models/base.py Normal file
View File

@ -0,0 +1,24 @@
import datetime
from typing import Any
from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
"""Base class for all models."""
id: Any
__name__: str
# Generate __tablename__ automatically based on class name
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
created_at = Column(DateTime, default=datetime.datetime.utcnow)
updated_at = Column(
DateTime,
default=datetime.datetime.utcnow,
onupdate=datetime.datetime.utcnow
)

69
app/models/rental.py Normal file
View File

@ -0,0 +1,69 @@
from sqlalchemy import Boolean, Column, Date, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from app.models.base import Base
class Category(Base):
"""Rental item categories."""
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True, nullable=False)
description = Column(Text, nullable=True)
# Relationship
items = relationship("RentalItem", back_populates="category")
def __repr__(self):
return f"<Category {self.name}>"
class RentalItem(Base):
"""Rental items available for rent."""
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True, nullable=False)
description = Column(Text, nullable=True)
daily_rate = Column(Float, nullable=False)
is_available = Column(Boolean, default=True, nullable=False)
category_id = Column(Integer, ForeignKey("category.id"), nullable=False)
# Relationships
category = relationship("Category", back_populates="items")
rental_records = relationship("RentalRecord", back_populates="item")
def __repr__(self):
return f"<RentalItem {self.name}>"
class Customer(Base):
"""Customer information."""
id = Column(Integer, primary_key=True, index=True)
first_name = Column(String, nullable=False)
last_name = Column(String, nullable=False)
email = Column(String, unique=True, index=True, nullable=False)
phone = Column(String, nullable=True)
address = Column(Text, nullable=True)
# Relationship
rental_records = relationship("RentalRecord", back_populates="customer")
def __repr__(self):
return f"<Customer {self.first_name} {self.last_name}>"
class RentalRecord(Base):
"""Records of rental transactions."""
id = Column(Integer, primary_key=True, index=True)
item_id = Column(Integer, ForeignKey("rentalitem.id"), nullable=False)
customer_id = Column(Integer, ForeignKey("customer.id"), nullable=False)
rental_date = Column(Date, nullable=False)
return_date = Column(Date, nullable=False)
actual_return_date = Column(Date, nullable=True)
total_cost = Column(Float, nullable=False)
notes = Column(Text, nullable=True)
# Relationships
item = relationship("RentalItem", back_populates="rental_records")
customer = relationship("Customer", back_populates="rental_records")
def __repr__(self):
return f"<RentalRecord {self.id}>"

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

@ -0,0 +1,8 @@
from app.schemas.category import Category, CategoryCreate, CategoryUpdate
from app.schemas.customer import Customer, CustomerCreate, CustomerUpdate
from app.schemas.rental_item import RentalItem, RentalItemCreate, RentalItemUpdate
from app.schemas.rental_record import (
RentalRecord,
RentalRecordCreate,
RentalRecordUpdate,
)

35
app/schemas/category.py Normal file
View File

@ -0,0 +1,35 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
# Shared properties
class CategoryBase(BaseModel):
name: str
description: Optional[str] = None
# Properties to receive on category creation
class CategoryCreate(CategoryBase):
pass
# Properties to receive on category update
class CategoryUpdate(CategoryBase):
name: Optional[str] = None
# Properties shared by models stored in DB
class CategoryInDBBase(CategoryBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
# Properties to return to client
class Category(CategoryInDBBase):
pass

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

@ -0,0 +1,42 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
# Shared properties
class CustomerBase(BaseModel):
first_name: str
last_name: str
email: str # Using str instead of EmailStr to avoid additional dependency
phone: Optional[str] = None
address: Optional[str] = None
# Properties to receive on customer creation
class CustomerCreate(CustomerBase):
pass
# Properties to receive on customer update
class CustomerUpdate(CustomerBase):
first_name: Optional[str] = None
last_name: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
address: Optional[str] = None
# Properties shared by models stored in DB
class CustomerInDBBase(CustomerBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
# Properties to return to client
class Customer(CustomerInDBBase):
pass

View File

@ -0,0 +1,42 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
# Shared properties
class RentalItemBase(BaseModel):
name: str
description: Optional[str] = None
daily_rate: float
is_available: bool = True
category_id: int
# Properties to receive on rental item creation
class RentalItemCreate(RentalItemBase):
pass
# Properties to receive on rental item update
class RentalItemUpdate(RentalItemBase):
name: Optional[str] = None
description: Optional[str] = None
daily_rate: Optional[float] = None
is_available: Optional[bool] = None
category_id: Optional[int] = None
# Properties shared by models stored in DB
class RentalItemInDBBase(RentalItemBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
# Properties to return to client
class RentalItem(RentalItemInDBBase):
pass

View File

@ -0,0 +1,46 @@
from datetime import date, datetime
from typing import Optional
from pydantic import BaseModel
# Shared properties
class RentalRecordBase(BaseModel):
item_id: int
customer_id: int
rental_date: date
return_date: date
actual_return_date: Optional[date] = None
total_cost: float
notes: Optional[str] = None
# Properties to receive on rental record creation
class RentalRecordCreate(RentalRecordBase):
pass
# Properties to receive on rental record update
class RentalRecordUpdate(RentalRecordBase):
item_id: Optional[int] = None
customer_id: Optional[int] = None
rental_date: Optional[date] = None
return_date: Optional[date] = None
actual_return_date: Optional[date] = None
total_cost: Optional[float] = None
notes: Optional[str] = None
# Properties shared by models stored in DB
class RentalRecordInDBBase(RentalRecordBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
# Properties to return to client
class RentalRecord(RentalRecordInDBBase):
pass

36
main.py Normal file
View File

@ -0,0 +1,36 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set up CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router)
@app.get("/health", tags=["health"])
def health_check():
"""
Health check endpoint to verify the API is running
"""
return {"status": "healthy"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

0
migrations/__init__.py Normal file
View File

85
migrations/env.py Normal file
View File

@ -0,0 +1,85 @@
import os
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# Add the parent directory to sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
# Import the SQLAlchemy models
from app.models import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
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:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
is_sqlite = connection.dialect.name == 'sqlite'
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Use batch mode for SQLite
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

24
migrations/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,99 @@
"""Initial schema
Revision ID: 001
Revises:
Create Date: 2023-10-20
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create category table
op.create_table(
'category',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_category_id'), 'category', ['id'], unique=False)
op.create_index(op.f('ix_category_name'), 'category', ['name'], unique=False)
# Create rentalitem table
op.create_table(
'rentalitem',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('daily_rate', sa.Float(), nullable=False),
sa.Column('is_available', sa.Boolean(), nullable=False, default=True),
sa.Column('category_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['category_id'], ['category.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_rentalitem_id'), 'rentalitem', ['id'], unique=False)
op.create_index(op.f('ix_rentalitem_name'), 'rentalitem', ['name'], unique=False)
# Create customer table
op.create_table(
'customer',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('first_name', sa.String(), nullable=False),
sa.Column('last_name', sa.String(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('phone', sa.String(), nullable=True),
sa.Column('address', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_customer_id'), 'customer', ['id'], unique=False)
op.create_index(op.f('ix_customer_email'), 'customer', ['email'], unique=True)
# Create rentalrecord table
op.create_table(
'rentalrecord',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('item_id', sa.Integer(), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=False),
sa.Column('rental_date', sa.Date(), nullable=False),
sa.Column('return_date', sa.Date(), nullable=False),
sa.Column('actual_return_date', sa.Date(), nullable=True),
sa.Column('total_cost', sa.Float(), nullable=False),
sa.Column('notes', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['customer_id'], ['customer.id'], ),
sa.ForeignKeyConstraint(['item_id'], ['rentalitem.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_rentalrecord_id'), 'rentalrecord', ['id'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_rentalrecord_id'), table_name='rentalrecord')
op.drop_table('rentalrecord')
op.drop_index(op.f('ix_customer_email'), table_name='customer')
op.drop_index(op.f('ix_customer_id'), table_name='customer')
op.drop_table('customer')
op.drop_index(op.f('ix_rentalitem_name'), table_name='rentalitem')
op.drop_index(op.f('ix_rentalitem_id'), table_name='rentalitem')
op.drop_table('rentalitem')
op.drop_index(op.f('ix_category_name'), table_name='category')
op.drop_index(op.f('ix_category_id'), table_name='category')
op.drop_table('category')

31
pyproject.toml Normal file
View File

@ -0,0 +1,31 @@
[tool.ruff]
# Enable flake8-bugbear (`B`) rules.
line-length = 88
target-version = "py38"
exclude = [
".git",
".ruff_cache",
".venv",
"venv",
"__pypackages__",
"dist",
"build",
]
[tool.ruff.lint]
select = ["E", "F", "B", "I"]
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[tool.ruff.lint.mccabe]
# Unlike Flake8, default to a complexity level of 10.
max-complexity = 10
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "starlette"]
[tool.ruff.lint.per-file-ignores]
# Allow unused imports in `__init__.py` files
"__init__.py" = ["F401"]
# Ignore B008 in FastAPI endpoints (common pattern)
"app/api/v1/endpoints/*.py" = ["B008"]

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
fastapi>=0.104.0
uvicorn>=0.23.2
pydantic>=2.4.2
pydantic-settings>=2.0.3
sqlalchemy>=2.0.22
alembic>=1.12.0
python-dotenv>=1.0.0
ruff>=0.1.1