Create comprehensive FastAPI REST API service
- Set up FastAPI application with SQLite database - Implement User and Item models with relationships - Add CRUD operations for users and items - Configure Alembic for database migrations - Include API documentation at /docs and /redoc - Add health check endpoint at /health - Enable CORS for all origins - Structure code with proper separation of concerns
This commit is contained in:
parent
cd19e28b5f
commit
ac56a7b6e5
85
README.md
85
README.md
@ -1,3 +1,84 @@
|
||||
# FastAPI Application
|
||||
# REST API Service
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A comprehensive REST API built with FastAPI, SQLAlchemy, and SQLite.
|
||||
|
||||
## Features
|
||||
|
||||
- User management (CRUD operations)
|
||||
- Item management with user ownership
|
||||
- SQLite database with Alembic migrations
|
||||
- Automatic API documentation with FastAPI
|
||||
- CORS enabled for all origins
|
||||
- Health check endpoint
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
├── main.py # FastAPI application entry point
|
||||
├── requirements.txt # Python dependencies
|
||||
├── alembic.ini # Alembic configuration
|
||||
├── alembic/ # Database migrations
|
||||
├── app/
|
||||
│ ├── api/ # API routes
|
||||
│ ├── crud/ # Database operations
|
||||
│ ├── db/ # Database configuration
|
||||
│ ├── models/ # SQLAlchemy models
|
||||
│ └── schemas/ # Pydantic schemas
|
||||
└── storage/ # Application storage directory
|
||||
```
|
||||
|
||||
## 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 --reload
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- **GET /**: Service information and links
|
||||
- **GET /health**: Health check endpoint
|
||||
- **GET /docs**: Interactive API documentation
|
||||
- **GET /redoc**: Alternative API documentation
|
||||
|
||||
### Users
|
||||
- **POST /api/v1/users/**: Create a new user
|
||||
- **GET /api/v1/users/**: List all users
|
||||
- **GET /api/v1/users/{user_id}**: Get user by ID
|
||||
- **PUT /api/v1/users/{user_id}**: Update user
|
||||
- **DELETE /api/v1/users/{user_id}**: Delete user
|
||||
|
||||
### Items
|
||||
- **POST /api/v1/items/**: Create a new item
|
||||
- **GET /api/v1/items/**: List all items
|
||||
- **GET /api/v1/items/{item_id}**: Get item by ID
|
||||
- **PUT /api/v1/items/{item_id}**: Update item
|
||||
- **DELETE /api/v1/items/{item_id}**: Delete item
|
||||
- **GET /api/v1/items/users/{user_id}/items**: Get items by user
|
||||
|
||||
## Database
|
||||
|
||||
The application uses SQLite as the database, stored at `/app/storage/db/db.sqlite`.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
No environment variables are currently required for basic operation.
|
||||
|
||||
## Development
|
||||
|
||||
The application includes:
|
||||
- Automatic code formatting with Ruff
|
||||
- Database migrations with Alembic
|
||||
- Comprehensive CRUD operations
|
||||
- Input validation with Pydantic
|
||||
- Automatic API documentation
|
||||
|
41
alembic.ini
Normal file
41
alembic.ini
Normal file
@ -0,0 +1,41 @@
|
||||
[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
|
53
alembic/env.py
Normal file
53
alembic/env.py
Normal file
@ -0,0 +1,53 @@
|
||||
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.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
from app.db.base import Base
|
||||
from app.models.user import User # noqa: F401
|
||||
from app.models.item import Item # noqa: F401
|
||||
|
||||
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
24
alembic/script.py.mako
Normal 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"}
|
55
alembic/versions/001_initial_migration.py
Normal file
55
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,55 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2024-01-01 12: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 users table
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('email', sa.String(), nullable=False),
|
||||
sa.Column('hashed_password', sa.String(), nullable=False),
|
||||
sa.Column('full_name', sa.String(), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
|
||||
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
|
||||
|
||||
# Create items table
|
||||
op.create_table('items',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('owner_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_items_title'), 'items', ['title'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f('ix_items_title'), table_name='items')
|
||||
op.drop_index(op.f('ix_items_id'), table_name='items')
|
||||
op.drop_table('items')
|
||||
op.drop_index(op.f('ix_users_id'), table_name='users')
|
||||
op.drop_index(op.f('ix_users_email'), table_name='users')
|
||||
op.drop_table('users')
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/api_v1/__init__.py
Normal file
0
app/api/api_v1/__init__.py
Normal file
6
app/api/api_v1/api.py
Normal file
6
app/api/api_v1/api.py
Normal file
@ -0,0 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
from app.api.api_v1.endpoints import users, items
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||
api_router.include_router(items.router, prefix="/items", tags=["items"])
|
0
app/api/api_v1/endpoints/__init__.py
Normal file
0
app/api/api_v1/endpoints/__init__.py
Normal file
75
app/api/api_v1/endpoints/items.py
Normal file
75
app/api/api_v1/endpoints/items.py
Normal file
@ -0,0 +1,75 @@
|
||||
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("/", response_model=List[schemas.Item])
|
||||
def read_items(
|
||||
db: Session = Depends(get_db),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
) -> Any:
|
||||
items = crud.item.get_multi(db, skip=skip, limit=limit)
|
||||
return items
|
||||
|
||||
@router.post("/", response_model=schemas.Item)
|
||||
def create_item(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
item_in: schemas.ItemCreate,
|
||||
owner_id: int,
|
||||
) -> Any:
|
||||
item = crud.item.create_with_owner(db, obj_in=item_in, owner_id=owner_id)
|
||||
return item
|
||||
|
||||
@router.get("/{item_id}", response_model=schemas.Item)
|
||||
def read_item(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
item_id: int,
|
||||
) -> Any:
|
||||
item = crud.item.get(db, id=item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return item
|
||||
|
||||
@router.put("/{item_id}", response_model=schemas.Item)
|
||||
def update_item(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
item_id: int,
|
||||
item_in: schemas.ItemUpdate,
|
||||
) -> Any:
|
||||
item = crud.item.get(db, id=item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
item = crud.item.update(db, db_obj=item, obj_in=item_in)
|
||||
return item
|
||||
|
||||
@router.delete("/{item_id}")
|
||||
def delete_item(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
item_id: int,
|
||||
) -> Any:
|
||||
item = crud.item.get(db, id=item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
item = crud.item.remove(db, id=item_id)
|
||||
return {"message": "Item deleted successfully"}
|
||||
|
||||
@router.get("/users/{user_id}/items", response_model=List[schemas.Item])
|
||||
def read_user_items(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_id: int,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
) -> Any:
|
||||
items = crud.item.get_multi_by_owner(
|
||||
db, owner_id=user_id, skip=skip, limit=limit
|
||||
)
|
||||
return items
|
67
app/api/api_v1/endpoints/users.py
Normal file
67
app/api/api_v1/endpoints/users.py
Normal file
@ -0,0 +1,67 @@
|
||||
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.post("/", response_model=schemas.User)
|
||||
def create_user(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_in: schemas.UserCreate,
|
||||
) -> Any:
|
||||
user = crud.user.get_by_email(db, email=user_in.email)
|
||||
if user:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="The user with this email already exists in the system.",
|
||||
)
|
||||
user = crud.user.create(db, obj_in=user_in)
|
||||
return user
|
||||
|
||||
@router.get("/", response_model=List[schemas.User])
|
||||
def read_users(
|
||||
db: Session = Depends(get_db),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
) -> Any:
|
||||
users = crud.user.get_multi(db, skip=skip, limit=limit)
|
||||
return users
|
||||
|
||||
@router.get("/{user_id}", response_model=schemas.User)
|
||||
def read_user(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_id: int,
|
||||
) -> Any:
|
||||
user = crud.user.get(db, id=user_id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return user
|
||||
|
||||
@router.put("/{user_id}", response_model=schemas.User)
|
||||
def update_user(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_id: int,
|
||||
user_in: schemas.UserUpdate,
|
||||
) -> Any:
|
||||
user = crud.user.get(db, id=user_id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
user = crud.user.update(db, db_obj=user, obj_in=user_in)
|
||||
return user
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
def delete_user(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_id: int,
|
||||
) -> Any:
|
||||
user = crud.user.get(db, id=user_id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
user = crud.user.remove(db, id=user_id)
|
||||
return {"message": "User deleted successfully"}
|
4
app/crud/__init__.py
Normal file
4
app/crud/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
from .user import user
|
||||
from .item import item
|
||||
|
||||
__all__ = ["user", "item"]
|
52
app/crud/base.py
Normal file
52
app/crud/base.py
Normal file
@ -0,0 +1,52 @@
|
||||
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.base import Base
|
||||
|
||||
ModelType = TypeVar("ModelType", bound=Base)
|
||||
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
|
||||
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
|
||||
|
||||
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
||||
def __init__(self, model: Type[ModelType]):
|
||||
self.model = model
|
||||
|
||||
def get(self, db: Session, id: Any) -> Optional[ModelType]:
|
||||
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]:
|
||||
return db.query(self.model).offset(skip).limit(limit).all()
|
||||
|
||||
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
|
||||
obj_in_data = obj_in.dict()
|
||||
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:
|
||||
if isinstance(obj_in, dict):
|
||||
update_data = obj_in
|
||||
else:
|
||||
update_data = obj_in.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_obj, field, value)
|
||||
db.add(db_obj)
|
||||
db.commit()
|
||||
db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
def remove(self, db: Session, *, id: int) -> ModelType:
|
||||
obj = db.query(self.model).get(id)
|
||||
db.delete(obj)
|
||||
db.commit()
|
||||
return obj
|
29
app/crud/item.py
Normal file
29
app/crud/item.py
Normal file
@ -0,0 +1,29 @@
|
||||
from typing import List
|
||||
from sqlalchemy.orm import Session
|
||||
from app.crud.base import CRUDBase
|
||||
from app.models.item import Item
|
||||
from app.schemas.item import ItemCreate, ItemUpdate
|
||||
|
||||
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
|
||||
def create_with_owner(
|
||||
self, db: Session, *, obj_in: ItemCreate, owner_id: int
|
||||
) -> Item:
|
||||
obj_in_data = obj_in.dict()
|
||||
db_obj = self.model(**obj_in_data, owner_id=owner_id)
|
||||
db.add(db_obj)
|
||||
db.commit()
|
||||
db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
def get_multi_by_owner(
|
||||
self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100
|
||||
) -> List[Item]:
|
||||
return (
|
||||
db.query(self.model)
|
||||
.filter(Item.owner_id == owner_id)
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
item = CRUDItem(Item)
|
38
app/crud/user.py
Normal file
38
app/crud/user.py
Normal file
@ -0,0 +1,38 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from passlib.context import CryptContext
|
||||
from app.crud.base import CRUDBase
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserUpdate
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
|
||||
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
|
||||
def create(self, db: Session, *, obj_in: UserCreate) -> User:
|
||||
hashed_password = pwd_context.hash(obj_in.password)
|
||||
db_obj = User(
|
||||
email=obj_in.email,
|
||||
hashed_password=hashed_password,
|
||||
full_name=obj_in.full_name,
|
||||
is_active=obj_in.is_active,
|
||||
)
|
||||
db.add(db_obj)
|
||||
db.commit()
|
||||
db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
|
||||
user = self.get_by_email(db, email=email)
|
||||
if not user:
|
||||
return None
|
||||
if not pwd_context.verify(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
||||
|
||||
def is_active(self, user: User) -> bool:
|
||||
return user.is_active
|
||||
|
||||
user = CRUDUser(User)
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
Base = declarative_base()
|
22
app/db/session.py
Normal file
22
app/db/session.py
Normal file
@ -0,0 +1,22 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from pathlib import Path
|
||||
|
||||
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()
|
4
app/models/__init__.py
Normal file
4
app/models/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
from .user import User
|
||||
from .item import Item
|
||||
|
||||
__all__ = ["User", "Item"]
|
16
app/models/item.py
Normal file
16
app/models/item.py
Normal file
@ -0,0 +1,16 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.db.base import Base
|
||||
|
||||
class Item(Base):
|
||||
__tablename__ = "items"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String, index=True, nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
owner_id = Column(Integer, ForeignKey("users.id"))
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
owner = relationship("User", back_populates="items")
|
17
app/models/user.py
Normal file
17
app/models/user.py
Normal file
@ -0,0 +1,17 @@
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.db.base import Base
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String, unique=True, index=True, nullable=False)
|
||||
hashed_password = Column(String, nullable=False)
|
||||
full_name = Column(String, nullable=True)
|
||||
is_active = Column(Boolean, default=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
items = relationship("Item", back_populates="owner")
|
4
app/schemas/__init__.py
Normal file
4
app/schemas/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
from .user import User, UserCreate, UserUpdate
|
||||
from .item import Item, ItemCreate, ItemUpdate
|
||||
|
||||
__all__ = ["User", "UserCreate", "UserUpdate", "Item", "ItemCreate", "ItemUpdate"]
|
23
app/schemas/item.py
Normal file
23
app/schemas/item.py
Normal file
@ -0,0 +1,23 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
class ItemBase(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
|
||||
class ItemCreate(ItemBase):
|
||||
pass
|
||||
|
||||
class ItemUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
class Item(ItemBase):
|
||||
id: int
|
||||
owner_id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
25
app/schemas/user.py
Normal file
25
app/schemas/user.py
Normal file
@ -0,0 +1,25 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
class UserBase(BaseModel):
|
||||
email: str
|
||||
full_name: Optional[str] = None
|
||||
is_active: bool = True
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
email: Optional[str] = None
|
||||
full_name: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
password: Optional[str] = None
|
||||
|
||||
class User(UserBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
47
main.py
Normal file
47
main.py
Normal file
@ -0,0 +1,47 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.api_v1.api import api_router
|
||||
from app.db.session import engine
|
||||
from app.db.base import Base
|
||||
|
||||
# Create database tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="REST API Service",
|
||||
description="A comprehensive REST API built with FastAPI",
|
||||
version="1.0.0",
|
||||
openapi_url="/openapi.json",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc"
|
||||
)
|
||||
|
||||
# Configure CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include API routes
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"title": "REST API Service",
|
||||
"description": "A comprehensive REST API built with FastAPI",
|
||||
"documentation": "/docs",
|
||||
"health_check": "/health"
|
||||
}
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": "REST API Service",
|
||||
"version": "1.0.0"
|
||||
}
|
10
requirements.txt
Normal file
10
requirements.txt
Normal file
@ -0,0 +1,10 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
alembic==1.12.1
|
||||
pydantic==2.5.0
|
||||
python-multipart==0.0.6
|
||||
passlib==1.7.4
|
||||
python-jose==3.3.0
|
||||
bcrypt==4.1.2
|
||||
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user