Initial Travel App Backend Implementation
- FastAPI application with user management, destinations, and trip planning - SQLite database with SQLAlchemy ORM - Database models for Users, Destinations, and Trips - Pydantic schemas for request/response validation - Full CRUD API endpoints for all resources - Alembic migrations setup - Health check endpoint - CORS configuration for development - Comprehensive documentation and README
This commit is contained in:
parent
1356a2afd7
commit
2de9589e3d
139
README.md
139
README.md
@ -1,3 +1,138 @@
|
|||||||
# FastAPI Application
|
# Travel App Backend
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A FastAPI-based backend application for a travel planning and management system.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **User Management**: Create and manage user accounts
|
||||||
|
- **Destination Management**: Add, update, and browse travel destinations
|
||||||
|
- **Trip Planning**: Create and manage travel trips with destinations, dates, and budgets
|
||||||
|
- **RESTful API**: Full CRUD operations for all resources
|
||||||
|
- **Database Integration**: SQLite database with SQLAlchemy ORM
|
||||||
|
- **API Documentation**: Automatic OpenAPI documentation
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- **Framework**: FastAPI
|
||||||
|
- **Database**: SQLite
|
||||||
|
- **ORM**: SQLAlchemy
|
||||||
|
- **Migrations**: Alembic
|
||||||
|
- **Validation**: Pydantic
|
||||||
|
- **Server**: Uvicorn
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Run database migrations:
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Start the server:
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at `http://localhost:8000`
|
||||||
|
|
||||||
|
## API Documentation
|
||||||
|
|
||||||
|
- **Interactive Docs**: http://localhost:8000/docs
|
||||||
|
- **ReDoc**: http://localhost:8000/redoc
|
||||||
|
- **OpenAPI JSON**: http://localhost:8000/openapi.json
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Root
|
||||||
|
- `GET /` - API information and links
|
||||||
|
- `GET /health` - Health check endpoint
|
||||||
|
|
||||||
|
### Users
|
||||||
|
- `GET /api/users/` - List all users
|
||||||
|
- `GET /api/users/{user_id}` - Get user by ID
|
||||||
|
- `POST /api/users/` - Create new user
|
||||||
|
- `PUT /api/users/{user_id}` - Update user
|
||||||
|
|
||||||
|
### Destinations
|
||||||
|
- `GET /api/destinations/` - List all destinations
|
||||||
|
- `GET /api/destinations/{destination_id}` - Get destination by ID
|
||||||
|
- `POST /api/destinations/` - Create new destination
|
||||||
|
- `PUT /api/destinations/{destination_id}` - Update destination
|
||||||
|
- `DELETE /api/destinations/{destination_id}` - Delete destination
|
||||||
|
|
||||||
|
### Trips
|
||||||
|
- `GET /api/trips/` - List all trips
|
||||||
|
- `GET /api/trips/{trip_id}` - Get trip by ID
|
||||||
|
- `GET /api/trips/user/{user_id}` - Get trips for specific user
|
||||||
|
- `POST /api/trips/` - Create new trip
|
||||||
|
- `PUT /api/trips/{trip_id}` - Update trip
|
||||||
|
- `DELETE /api/trips/{trip_id}` - Delete trip
|
||||||
|
|
||||||
|
## Database Schema
|
||||||
|
|
||||||
|
### Users
|
||||||
|
- `id`: Primary key
|
||||||
|
- `email`: Unique email address
|
||||||
|
- `full_name`: User's full name
|
||||||
|
- `hashed_password`: Encrypted password
|
||||||
|
- `is_active`: Account status
|
||||||
|
- `created_at`: Account creation timestamp
|
||||||
|
- `updated_at`: Last update timestamp
|
||||||
|
|
||||||
|
### Destinations
|
||||||
|
- `id`: Primary key
|
||||||
|
- `name`: Destination name
|
||||||
|
- `country`: Country name
|
||||||
|
- `city`: City name
|
||||||
|
- `description`: Destination description
|
||||||
|
- `latitude`: GPS latitude
|
||||||
|
- `longitude`: GPS longitude
|
||||||
|
- `rating`: Destination rating (0-5)
|
||||||
|
- `image_url`: Destination image URL
|
||||||
|
- `created_at`: Creation timestamp
|
||||||
|
- `updated_at`: Last update timestamp
|
||||||
|
|
||||||
|
### Trips
|
||||||
|
- `id`: Primary key
|
||||||
|
- `title`: Trip title
|
||||||
|
- `description`: Trip description
|
||||||
|
- `user_id`: Foreign key to Users table
|
||||||
|
- `destination_id`: Foreign key to Destinations table
|
||||||
|
- `start_date`: Trip start date
|
||||||
|
- `end_date`: Trip end date
|
||||||
|
- `budget`: Trip budget
|
||||||
|
- `status`: Trip status (planned, ongoing, completed, cancelled)
|
||||||
|
- `created_at`: Creation timestamp
|
||||||
|
- `updated_at`: Last update timestamp
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Running with Ruff
|
||||||
|
```bash
|
||||||
|
ruff check .
|
||||||
|
ruff format .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Migrations
|
||||||
|
```bash
|
||||||
|
# Create new migration
|
||||||
|
alembic revision --autogenerate -m "Description"
|
||||||
|
|
||||||
|
# Apply migrations
|
||||||
|
alembic upgrade head
|
||||||
|
|
||||||
|
# Rollback migration
|
||||||
|
alembic downgrade -1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Storage
|
||||||
|
|
||||||
|
The application uses `/app/storage/db/` directory for SQLite database storage.
|
||||||
|
|
||||||
|
## CORS Configuration
|
||||||
|
|
||||||
|
The API is configured to allow all origins (*) for development purposes.
|
||||||
|
42
alembic.ini
Normal file
42
alembic.ini
Normal 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
|
50
alembic/env.py
Normal file
50
alembic/env.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from alembic import context
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.append(str(Path(__file__).parent.parent))
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
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"}
|
106
alembic/versions/001_initial_migration.py
Normal file
106
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
"""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("full_name", sa.String(), nullable=False),
|
||||||
|
sa.Column("hashed_password", sa.String(), nullable=False),
|
||||||
|
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 destinations table
|
||||||
|
op.create_table(
|
||||||
|
"destinations",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(), nullable=False),
|
||||||
|
sa.Column("country", sa.String(), nullable=False),
|
||||||
|
sa.Column("city", sa.String(), nullable=False),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column("latitude", sa.Float(), nullable=True),
|
||||||
|
sa.Column("longitude", sa.Float(), nullable=True),
|
||||||
|
sa.Column("rating", sa.Float(), nullable=True),
|
||||||
|
sa.Column("image_url", 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.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_destinations_id"), "destinations", ["id"], unique=False)
|
||||||
|
op.create_index(
|
||||||
|
op.f("ix_destinations_name"), "destinations", ["name"], unique=False
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create trips table
|
||||||
|
op.create_table(
|
||||||
|
"trips",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("title", sa.String(), nullable=False),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("destination_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("start_date", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("end_date", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("budget", sa.Float(), nullable=True),
|
||||||
|
sa.Column("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(
|
||||||
|
["destination_id"],
|
||||||
|
["destinations.id"],
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["user_id"],
|
||||||
|
["users.id"],
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_trips_id"), "trips", ["id"], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_trips_id"), table_name="trips")
|
||||||
|
op.drop_table("trips")
|
||||||
|
op.drop_index(op.f("ix_destinations_name"), table_name="destinations")
|
||||||
|
op.drop_index(op.f("ix_destinations_id"), table_name="destinations")
|
||||||
|
op.drop_table("destinations")
|
||||||
|
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")
|
67
app/api/destinations.py
Normal file
67
app/api/destinations.py
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
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.destination import Destination
|
||||||
|
from app.schemas.destination import (
|
||||||
|
Destination as DestinationSchema,
|
||||||
|
DestinationCreate,
|
||||||
|
DestinationUpdate,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[DestinationSchema])
|
||||||
|
def get_destinations(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||||
|
destinations = db.query(Destination).offset(skip).limit(limit).all()
|
||||||
|
return destinations
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{destination_id}", response_model=DestinationSchema)
|
||||||
|
def get_destination(destination_id: int, db: Session = Depends(get_db)):
|
||||||
|
destination = db.query(Destination).filter(Destination.id == destination_id).first()
|
||||||
|
if destination is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
return destination
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=DestinationSchema)
|
||||||
|
def create_destination(destination: DestinationCreate, db: Session = Depends(get_db)):
|
||||||
|
db_destination = Destination(**destination.dict())
|
||||||
|
db.add(db_destination)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_destination)
|
||||||
|
return db_destination
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{destination_id}", response_model=DestinationSchema)
|
||||||
|
def update_destination(
|
||||||
|
destination_id: int, destination: DestinationUpdate, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
db_destination = (
|
||||||
|
db.query(Destination).filter(Destination.id == destination_id).first()
|
||||||
|
)
|
||||||
|
if db_destination is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
|
||||||
|
update_data = destination.dict(exclude_unset=True)
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(db_destination, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_destination)
|
||||||
|
return db_destination
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{destination_id}")
|
||||||
|
def delete_destination(destination_id: int, db: Session = Depends(get_db)):
|
||||||
|
db_destination = (
|
||||||
|
db.query(Destination).filter(Destination.id == destination_id).first()
|
||||||
|
)
|
||||||
|
if db_destination is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
|
||||||
|
db.delete(db_destination)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "Destination deleted successfully"}
|
92
app/api/trips.py
Normal file
92
app/api/trips.py
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
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.trip import Trip
|
||||||
|
from app.models.user import User
|
||||||
|
from app.models.destination import Destination
|
||||||
|
from app.schemas.trip import Trip as TripSchema, TripCreate, TripUpdate
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[TripSchema])
|
||||||
|
def get_trips(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||||
|
trips = db.query(Trip).offset(skip).limit(limit).all()
|
||||||
|
return trips
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{trip_id}", response_model=TripSchema)
|
||||||
|
def get_trip(trip_id: int, db: Session = Depends(get_db)):
|
||||||
|
trip = db.query(Trip).filter(Trip.id == trip_id).first()
|
||||||
|
if trip is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Trip not found")
|
||||||
|
return trip
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/user/{user_id}", response_model=List[TripSchema])
|
||||||
|
def get_user_trips(
|
||||||
|
user_id: int, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
|
||||||
|
trips = (
|
||||||
|
db.query(Trip).filter(Trip.user_id == user_id).offset(skip).limit(limit).all()
|
||||||
|
)
|
||||||
|
return trips
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=TripSchema)
|
||||||
|
def create_trip(trip: TripCreate, user_id: int, db: Session = Depends(get_db)):
|
||||||
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
|
||||||
|
destination = (
|
||||||
|
db.query(Destination).filter(Destination.id == trip.destination_id).first()
|
||||||
|
)
|
||||||
|
if destination is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
|
||||||
|
db_trip = Trip(**trip.dict(), user_id=user_id)
|
||||||
|
db.add(db_trip)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_trip)
|
||||||
|
return db_trip
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{trip_id}", response_model=TripSchema)
|
||||||
|
def update_trip(trip_id: int, trip: TripUpdate, db: Session = Depends(get_db)):
|
||||||
|
db_trip = db.query(Trip).filter(Trip.id == trip_id).first()
|
||||||
|
if db_trip is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Trip not found")
|
||||||
|
|
||||||
|
update_data = trip.dict(exclude_unset=True)
|
||||||
|
if "destination_id" in update_data:
|
||||||
|
destination = (
|
||||||
|
db.query(Destination)
|
||||||
|
.filter(Destination.id == update_data["destination_id"])
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if destination is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Destination not found")
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(db_trip, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_trip)
|
||||||
|
return db_trip
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{trip_id}")
|
||||||
|
def delete_trip(trip_id: int, db: Session = Depends(get_db)):
|
||||||
|
db_trip = db.query(Trip).filter(Trip.id == trip_id).first()
|
||||||
|
if db_trip is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Trip not found")
|
||||||
|
|
||||||
|
db.delete(db_trip)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "Trip deleted successfully"}
|
60
app/api/users.py
Normal file
60
app/api/users.py
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
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.schemas.user import User as UserSchema, UserCreate, UserUpdate
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
def get_password_hash(password: str) -> str:
|
||||||
|
return f"hashed_{password}"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[UserSchema])
|
||||||
|
def get_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||||
|
users = db.query(User).offset(skip).limit(limit).all()
|
||||||
|
return users
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}", response_model=UserSchema)
|
||||||
|
def get_user(user_id: int, db: Session = Depends(get_db)):
|
||||||
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=UserSchema)
|
||||||
|
def create_user(user: UserCreate, db: Session = Depends(get_db)):
|
||||||
|
db_user = db.query(User).filter(User.email == user.email).first()
|
||||||
|
if db_user:
|
||||||
|
raise HTTPException(status_code=400, detail="Email already registered")
|
||||||
|
|
||||||
|
hashed_password = get_password_hash(user.password)
|
||||||
|
db_user = User(
|
||||||
|
email=user.email, full_name=user.full_name, hashed_password=hashed_password
|
||||||
|
)
|
||||||
|
db.add(db_user)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_user)
|
||||||
|
return db_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}", response_model=UserSchema)
|
||||||
|
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
|
||||||
|
db_user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if db_user is None:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
|
||||||
|
update_data = user.dict(exclude_unset=True)
|
||||||
|
if "password" in update_data:
|
||||||
|
update_data["hashed_password"] = get_password_hash(update_data.pop("password"))
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(db_user, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_user)
|
||||||
|
return db_user
|
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 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()
|
22
app/models/destination.py
Normal file
22
app/models/destination.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text, Float, DateTime
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Destination(Base):
|
||||||
|
__tablename__ = "destinations"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False, index=True)
|
||||||
|
country = Column(String, nullable=False)
|
||||||
|
city = Column(String, nullable=False)
|
||||||
|
description = Column(Text)
|
||||||
|
latitude = Column(Float)
|
||||||
|
longitude = Column(Float)
|
||||||
|
rating = Column(Float, default=0.0)
|
||||||
|
image_url = Column(String)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
trips = relationship("Trip", back_populates="destination")
|
23
app/models/trip.py
Normal file
23
app/models/trip.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Float
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Trip(Base):
|
||||||
|
__tablename__ = "trips"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
title = Column(String, nullable=False)
|
||||||
|
description = Column(Text)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
|
destination_id = Column(Integer, ForeignKey("destinations.id"), nullable=False)
|
||||||
|
start_date = Column(DateTime, nullable=False)
|
||||||
|
end_date = Column(DateTime, nullable=False)
|
||||||
|
budget = Column(Float)
|
||||||
|
status = Column(String, default="planned") # planned, ongoing, completed, cancelled
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="trips")
|
||||||
|
destination = relationship("Destination", back_populates="trips")
|
18
app/models/user.py
Normal file
18
app/models/user.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, DateTime, Boolean
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
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)
|
||||||
|
full_name = Column(String, nullable=False)
|
||||||
|
hashed_password = Column(String, nullable=False)
|
||||||
|
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())
|
||||||
|
|
||||||
|
trips = relationship("Trip", back_populates="user")
|
38
app/schemas/destination.py
Normal file
38
app/schemas/destination.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationBase(BaseModel):
|
||||||
|
name: str
|
||||||
|
country: str
|
||||||
|
city: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
latitude: Optional[float] = None
|
||||||
|
longitude: Optional[float] = None
|
||||||
|
rating: Optional[float] = 0.0
|
||||||
|
image_url: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationCreate(DestinationBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DestinationUpdate(BaseModel):
|
||||||
|
name: Optional[str] = None
|
||||||
|
country: Optional[str] = None
|
||||||
|
city: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
latitude: Optional[float] = None
|
||||||
|
longitude: Optional[float] = None
|
||||||
|
rating: Optional[float] = None
|
||||||
|
image_url: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Destination(DestinationBase):
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
41
app/schemas/trip.py
Normal file
41
app/schemas/trip.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from .user import User
|
||||||
|
from .destination import Destination
|
||||||
|
|
||||||
|
|
||||||
|
class TripBase(BaseModel):
|
||||||
|
title: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
destination_id: int
|
||||||
|
start_date: datetime
|
||||||
|
end_date: datetime
|
||||||
|
budget: Optional[float] = None
|
||||||
|
status: Optional[str] = "planned"
|
||||||
|
|
||||||
|
|
||||||
|
class TripCreate(TripBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TripUpdate(BaseModel):
|
||||||
|
title: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
destination_id: Optional[int] = None
|
||||||
|
start_date: Optional[datetime] = None
|
||||||
|
end_date: Optional[datetime] = None
|
||||||
|
budget: Optional[float] = None
|
||||||
|
status: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Trip(TripBase):
|
||||||
|
id: int
|
||||||
|
user_id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
user: Optional[User] = None
|
||||||
|
destination: Optional[Destination] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
27
app/schemas/user.py
Normal file
27
app/schemas/user.py
Normal 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: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
password: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class User(UserBase):
|
||||||
|
id: int
|
||||||
|
is_active: bool
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
51
main.py
Normal file
51
main.py
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from app.api import users, destinations, trips
|
||||||
|
from app.db.session import engine
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Travel App API",
|
||||||
|
description="A travel planning and management API",
|
||||||
|
version="1.0.0",
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
docs_url="/docs",
|
||||||
|
redoc_url="/redoc",
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def read_root():
|
||||||
|
return {
|
||||||
|
"title": "Travel App API",
|
||||||
|
"description": "A travel planning and management API",
|
||||||
|
"documentation": "/docs",
|
||||||
|
"health": "/health",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health_check():
|
||||||
|
return {"status": "healthy", "service": "Travel App API", "version": "1.0.0"}
|
||||||
|
|
||||||
|
|
||||||
|
app.include_router(users.router, prefix="/api/users", tags=["users"])
|
||||||
|
app.include_router(
|
||||||
|
destinations.router, prefix="/api/destinations", tags=["destinations"]
|
||||||
|
)
|
||||||
|
app.include_router(trips.router, prefix="/api/trips", tags=["trips"])
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|
8
requirements.txt
Normal file
8
requirements.txt
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
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
|
||||||
|
email-validator==2.1.0
|
||||||
|
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user