Add complete FastAPI backend for AI tutor application

- User authentication with JWT tokens (register/login)
- Tutor session management with CRUD operations
- Message tracking for tutor conversations
- SQLite database with Alembic migrations
- CORS configuration for frontend integration
- Health check and service info endpoints
- Proper project structure with models, schemas, and API routes
This commit is contained in:
Automated Action 2025-06-23 17:55:19 +00:00
parent c9e5d6a47e
commit 07f6a51f6f
24 changed files with 733 additions and 2 deletions

View File

@ -1,3 +1,77 @@
# FastAPI Application
# AI Tutor Backend Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A FastAPI-based backend service for an AI-powered tutoring application.
## Features
- User authentication (register/login with JWT tokens)
- Tutor session management
- Message tracking for tutor conversations
- SQLite database with Alembic migrations
- CORS enabled for frontend integration
- Health check endpoint
## Environment Variables
Copy `.env.example` to `.env` and set the following variables:
- `SECRET_KEY`: JWT secret key for token generation (required for production)
## Installation
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run database migrations:
```bash
alembic upgrade head
```
3. Start the development server:
```bash
uvicorn main:app --reload
```
The API will be available at `http://localhost:8000`
## API Documentation
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
- OpenAPI JSON: `http://localhost:8000/openapi.json`
## API Endpoints
### Authentication
- `POST /auth/register` - Register a new user
- `POST /auth/login` - Login and get access token
- `GET /auth/me` - Get current user profile
### Tutor Sessions
- `POST /tutor/sessions` - Create a new tutor session
- `GET /tutor/sessions` - Get all user sessions
- `GET /tutor/sessions/{session_id}` - Get specific session
- `PUT /tutor/sessions/{session_id}` - Update session
- `POST /tutor/sessions/{session_id}/messages` - Add message to session
- `GET /tutor/sessions/{session_id}/messages` - Get session messages
### Health
- `GET /health` - Health check endpoint
- `GET /` - Service information
## Database
The application uses SQLite database stored at `/app/storage/db/db.sqlite`. The database includes:
- `users` - User accounts
- `tutor_sessions` - Tutoring sessions
- `tutor_messages` - Messages within sessions
## Development
To run in development mode:
```bash
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```

41
alembic.ini Normal file
View 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

55
alembic/env.py Normal file
View File

@ -0,0 +1,55 @@
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(__file__)))
from app.db.base import Base
from app.models.user import User
from app.models.tutor_session import TutorSession
from app.models.tutor_message import TutorMessage
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,64 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2024-01-01 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
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)
op.create_table('tutor_sessions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('subject', sa.String(), nullable=False),
sa.Column('topic', sa.String(), nullable=True),
sa.Column('difficulty_level', sa.String(), nullable=True),
sa.Column('session_status', sa.String(), 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(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_tutor_sessions_id'), 'tutor_sessions', ['id'], unique=False)
op.create_table('tutor_messages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('session_id', sa.Integer(), nullable=False),
sa.Column('message_type', sa.String(), nullable=False),
sa.Column('content', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
sa.ForeignKeyConstraint(['session_id'], ['tutor_sessions.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_tutor_messages_id'), 'tutor_messages', ['id'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_tutor_messages_id'), table_name='tutor_messages')
op.drop_table('tutor_messages')
op.drop_index(op.f('ix_tutor_sessions_id'), table_name='tutor_sessions')
op.drop_table('tutor_sessions')
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
View File

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

95
app/api/auth.py Normal file
View File

@ -0,0 +1,95 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from jose import JWTError, jwt
from app.db.session import get_db
from app.models.user import User
from app.schemas.user import UserCreate, UserLogin, User as UserSchema
from app.core.security import (
verify_password,
get_password_hash,
create_access_token,
SECRET_KEY,
ALGORITHM
)
router = APIRouter()
security = HTTPBearer()
def get_user_by_email(db: Session, email: str):
return db.query(User).filter(User.email == email).first()
def create_user(db: Session, user: UserCreate):
hashed_password = get_password_hash(user.password)
db_user = User(
email=user.email,
hashed_password=hashed_password,
full_name=user.full_name,
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def authenticate_user(db: Session, email: str, password: str):
user = get_user_by_email(db, email)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
user_id: int = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = db.query(User).filter(User.id == user_id).first()
if user is None:
raise credentials_exception
return user
@router.post("/register", response_model=UserSchema)
def register(user: UserCreate, db: Session = Depends(get_db)):
db_user = get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(
status_code=400,
detail="Email already registered"
)
return create_user(db=db, user=user)
@router.post("/login")
def login(user_credentials: UserLogin, db: Session = Depends(get_db)):
user = authenticate_user(db, user_credentials.email, user_credentials.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(subject=user.id)
return {"access_token": access_token, "token_type": "bearer"}
@router.get("/me", response_model=UserSchema)
def read_users_me(current_user: User = Depends(get_current_user)):
return current_user

128
app/api/tutor.py Normal file
View File

@ -0,0 +1,128 @@
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.user import User
from app.models.tutor_session import TutorSession
from app.models.tutor_message import TutorMessage
from app.schemas.tutor_session import (
TutorSessionCreate,
TutorSessionUpdate,
TutorSession as TutorSessionSchema
)
from app.schemas.tutor_message import (
TutorMessageCreate,
TutorMessage as TutorMessageSchema
)
from app.api.auth import get_current_user
router = APIRouter()
@router.post("/sessions", response_model=TutorSessionSchema)
def create_tutor_session(
session: TutorSessionCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
db_session = TutorSession(
user_id=current_user.id,
subject=session.subject,
topic=session.topic,
difficulty_level=session.difficulty_level
)
db.add(db_session)
db.commit()
db.refresh(db_session)
return db_session
@router.get("/sessions", response_model=List[TutorSessionSchema])
def get_user_sessions(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
return db.query(TutorSession).filter(
TutorSession.user_id == current_user.id
).all()
@router.get("/sessions/{session_id}", response_model=TutorSessionSchema)
def get_session(
session_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
session = db.query(TutorSession).filter(
TutorSession.id == session_id,
TutorSession.user_id == current_user.id
).first()
if not session:
raise HTTPException(status_code=404, detail="Session not found")
return session
@router.put("/sessions/{session_id}", response_model=TutorSessionSchema)
def update_session(
session_id: int,
session_update: TutorSessionUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
session = db.query(TutorSession).filter(
TutorSession.id == session_id,
TutorSession.user_id == current_user.id
).first()
if not session:
raise HTTPException(status_code=404, detail="Session not found")
update_data = session_update.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(session, field, value)
db.commit()
db.refresh(session)
return session
@router.post("/sessions/{session_id}/messages", response_model=TutorMessageSchema)
def add_message_to_session(
session_id: int,
message: TutorMessageCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
session = db.query(TutorSession).filter(
TutorSession.id == session_id,
TutorSession.user_id == current_user.id
).first()
if not session:
raise HTTPException(status_code=404, detail="Session not found")
db_message = TutorMessage(
session_id=session_id,
message_type=message.message_type,
content=message.content
)
db.add(db_message)
db.commit()
db.refresh(db_message)
return db_message
@router.get("/sessions/{session_id}/messages", response_model=List[TutorMessageSchema])
def get_session_messages(
session_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
session = db.query(TutorSession).filter(
TutorSession.id == session_id,
TutorSession.user_id == current_user.id
).first()
if not session:
raise HTTPException(status_code=404, detail="Session not found")
return db.query(TutorMessage).filter(
TutorMessage.session_id == session_id
).order_by(TutorMessage.created_at).all()

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

33
app/core/security.py Normal file
View File

@ -0,0 +1,33 @@
import os
from datetime import datetime, timedelta
from typing import Any, Union
from jose import jwt
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-here")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
def create_access_token(
subject: Union[str, Any], expires_delta: timedelta = None
) -> str:
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)

0
app/db/__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
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()

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

View File

@ -0,0 +1,16 @@
from sqlalchemy import Column, Integer, Text, DateTime, String, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.db.base import Base
class TutorMessage(Base):
__tablename__ = "tutor_messages"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(Integer, ForeignKey("tutor_sessions.id"), nullable=False)
message_type = Column(String, nullable=False) # "user" or "tutor"
content = Column(Text, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
session = relationship("TutorSession", back_populates="messages")

View File

@ -0,0 +1,20 @@
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.db.base import Base
class TutorSession(Base):
__tablename__ = "tutor_sessions"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
subject = Column(String, nullable=False)
topic = Column(String, nullable=True)
difficulty_level = Column(String, nullable=True)
session_status = Column(String, default="active")
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
user = relationship("User", back_populates="tutor_sessions")
messages = relationship("TutorMessage", back_populates="session")

18
app/models/user.py Normal file
View File

@ -0,0 +1,18 @@
from sqlalchemy import Column, Integer, String, DateTime, Boolean
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())
tutor_sessions = relationship("TutorSession", back_populates="user")

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

View File

@ -0,0 +1,20 @@
from pydantic import BaseModel
from datetime import datetime
class TutorMessageBase(BaseModel):
message_type: str
content: str
class TutorMessageCreate(TutorMessageBase):
session_id: int
class TutorMessage(TutorMessageBase):
id: int
session_id: int
created_at: datetime
class Config:
from_attributes = True

View File

@ -0,0 +1,42 @@
from pydantic import BaseModel
from datetime import datetime
from typing import Optional, List
class TutorSessionBase(BaseModel):
subject: str
topic: Optional[str] = None
difficulty_level: Optional[str] = None
class TutorSessionCreate(TutorSessionBase):
pass
class TutorSessionUpdate(BaseModel):
subject: Optional[str] = None
topic: Optional[str] = None
difficulty_level: Optional[str] = None
session_status: Optional[str] = None
class TutorMessage(BaseModel):
id: int
message_type: str
content: str
created_at: datetime
class Config:
from_attributes = True
class TutorSession(TutorSessionBase):
id: int
user_id: int
session_status: str
created_at: datetime
updated_at: Optional[datetime] = None
messages: List[TutorMessage] = []
class Config:
from_attributes = True

27
app/schemas/user.py Normal file
View File

@ -0,0 +1,27 @@
from pydantic import BaseModel, EmailStr
from datetime import datetime
from typing import Optional
class UserBase(BaseModel):
email: EmailStr
full_name: Optional[str] = None
class UserCreate(UserBase):
password: str
class UserLogin(BaseModel):
email: EmailStr
password: str
class User(UserBase):
id: int
is_active: bool
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

39
main.py Normal file
View File

@ -0,0 +1,39 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api import auth, tutor
from app.db.session import engine
from app.db.base import Base
Base.metadata.create_all(bind=engine)
app = FastAPI(
title="AI Tutor Backend Service",
description="Backend API for AI-powered tutoring application",
version="1.0.0",
openapi_url="/openapi.json"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth.router, prefix="/auth", tags=["authentication"])
app.include_router(tutor.router, prefix="/tutor", tags=["tutor"])
@app.get("/")
def read_root():
return {
"title": "AI Tutor Backend Service",
"documentation": "/docs",
"health": "/health"
}
@app.get("/health")
def health_check():
return {"status": "healthy", "service": "AI Tutor Backend"}

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
fastapi==0.104.1
uvicorn[standard]==0.24.0
sqlalchemy==2.0.23
alembic==1.12.1
python-multipart==0.0.6
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-dotenv==1.0.0
ruff==0.1.6