feat: add GET endpoint for movie collection
This commit is contained in:
parent
5f030eac68
commit
adf5bc4f88
32
alembic/versions/20250507_210530_7da688da_update_movie.py
Normal file
32
alembic/versions/20250507_210530_7da688da_update_movie.py
Normal file
@ -0,0 +1,32 @@
|
||||
"""create table for movies
|
||||
Revision ID: 2b3c4d5e6f7a
|
||||
Revises: 0001
|
||||
Create Date: 2023-05-23 12:34:56
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2b3c4d5e6f7a'
|
||||
down_revision = '0001'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'movies',
|
||||
sa.Column('id', sa.String(36), primary_key=True, default=func.uuid_generate_v4()),
|
||||
sa.Column('title', sa.String(), nullable=False),
|
||||
sa.Column('description', sa.String(), nullable=True),
|
||||
sa.Column('release_year', sa.Integer(), nullable=False),
|
||||
sa.Column('runtime', sa.Integer(), nullable=True),
|
||||
sa.Column('rating', sa.Integer(), nullable=True),
|
||||
sa.Column('director_id', sa.String(36), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now(), onupdate=sa.func.now())
|
||||
)
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('movies')
|
@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from typing import List
|
||||
from schemas.movie import MovieSchema
|
||||
from helpers.movie_helpers import get_all_movies
|
||||
from sqlalchemy.orm import Session
|
||||
from core.database import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/movieapp", status_code=200, response_model=List[MovieSchema])
|
||||
async def get_movies(db: Session = Depends(get_db)):
|
||||
movies = get_all_movies(db)
|
||||
return movies
|
95
helpers/movie_helpers.py
Normal file
95
helpers/movie_helpers.py
Normal file
@ -0,0 +1,95 @@
|
||||
from typing import List, Optional, Dict, Any
|
||||
import uuid
|
||||
from sqlalchemy.orm import Session
|
||||
from models.movie import Movie
|
||||
from schemas.movie import MovieCreate, MovieSchema
|
||||
|
||||
def get_all_movies(db: Session) -> List[MovieSchema]:
|
||||
"""
|
||||
Retrieves all movies from the database.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
|
||||
Returns:
|
||||
List[MovieSchema]: A list of all movie objects.
|
||||
"""
|
||||
movies = db.query(Movie).all()
|
||||
return [MovieSchema.from_orm(movie) for movie in movies]
|
||||
|
||||
def create_movie(db: Session, movie_data: MovieCreate) -> MovieSchema:
|
||||
"""
|
||||
Creates a new movie in the database.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
movie_data (MovieCreate): The data for the movie to create.
|
||||
|
||||
Returns:
|
||||
MovieSchema: The newly created movie object.
|
||||
"""
|
||||
db_movie = Movie(**movie_data.dict())
|
||||
db.add(db_movie)
|
||||
db.commit()
|
||||
db.refresh(db_movie)
|
||||
return MovieSchema.from_orm(db_movie)
|
||||
|
||||
def get_movie_by_id(db: Session, movie_id: uuid.UUID) -> Optional[MovieSchema]:
|
||||
"""
|
||||
Retrieves a single movie by its ID.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
movie_id (UUID): The ID of the movie to retrieve.
|
||||
|
||||
Returns:
|
||||
Optional[MovieSchema]: The movie object if found, otherwise None.
|
||||
"""
|
||||
db_movie = db.query(Movie).filter(Movie.id == movie_id).first()
|
||||
if db_movie:
|
||||
return MovieSchema.from_orm(db_movie)
|
||||
return None
|
||||
|
||||
# In-memory store for movies (if no database model provided)
|
||||
_movies_store: List[Dict[str, Any]] = []
|
||||
|
||||
def create_movie_in_memory(movie_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Adds a movie to the in-memory list.
|
||||
|
||||
Args:
|
||||
movie_data (Dict[str, Any]): Data for the new movie.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The created movie data, with an added ID.
|
||||
"""
|
||||
if not movie_data.get("title"):
|
||||
raise ValueError("Movie title is required")
|
||||
new_movie = movie_data.copy()
|
||||
new_movie["id"] = str(uuid.uuid4())
|
||||
_movies_store.append(new_movie)
|
||||
return new_movie
|
||||
|
||||
def get_all_movies_in_memory() -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Retrieves all movies from the in-memory list.
|
||||
|
||||
Returns:
|
||||
List[Dict[str, Any]]: A list of all movies.
|
||||
"""
|
||||
return _movies_store
|
||||
|
||||
def get_movie_by_id_in_memory(movie_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Finds a movie by ID in the in-memory list.
|
||||
|
||||
Args:
|
||||
movie_id (str): The ID of the movie to find.
|
||||
|
||||
Returns:
|
||||
Optional[Dict[str, Any]]: The movie if found, otherwise None.
|
||||
"""
|
||||
for movie in _movies_store:
|
||||
if movie.get("id") == movie_id:
|
||||
return movie
|
||||
return None
|
20
models/movie.py
Normal file
20
models/movie.py
Normal file
@ -0,0 +1,20 @@
|
||||
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
from core.database import Base
|
||||
import uuid
|
||||
|
||||
class Movie(Base):
|
||||
__tablename__ = "movies"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
title = Column(String, nullable=False)
|
||||
description = Column(String, nullable=True)
|
||||
release_year = Column(Integer, nullable=False)
|
||||
runtime = Column(Integer, nullable=True)
|
||||
rating = Column(Integer, nullable=True)
|
||||
director_id = Column(UUID(as_uuid=True), ForeignKey("directors.id"), nullable=False)
|
||||
director = relationship("Director", back_populates="movies")
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
@ -7,3 +7,6 @@ sqlalchemy>=1.4.0
|
||||
python-dotenv>=0.19.0
|
||||
bcrypt>=3.2.0
|
||||
alembic>=1.13.1
|
||||
jose
|
||||
passlib
|
||||
pydantic
|
||||
|
31
schemas/movie.py
Normal file
31
schemas/movie.py
Normal file
@ -0,0 +1,31 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
|
||||
class MovieBase(BaseModel):
|
||||
title: str = Field(..., description="Movie title")
|
||||
description: Optional[str] = Field(None, description="Movie description")
|
||||
release_year: int = Field(..., description="Movie release year")
|
||||
runtime: Optional[int] = Field(None, description="Movie runtime in minutes")
|
||||
rating: Optional[int] = Field(None, description="Movie rating")
|
||||
director_id: uuid.UUID = Field(..., description="ID of the movie director")
|
||||
|
||||
class MovieCreate(MovieBase):
|
||||
pass
|
||||
|
||||
class MovieUpdate(MovieBase):
|
||||
title: Optional[str] = Field(None, description="Movie title")
|
||||
description: Optional[str] = Field(None, description="Movie description")
|
||||
release_year: Optional[int] = Field(None, description="Movie release year")
|
||||
runtime: Optional[int] = Field(None, description="Movie runtime in minutes")
|
||||
rating: Optional[int] = Field(None, description="Movie rating")
|
||||
director_id: Optional[uuid.UUID] = Field(None, description="ID of the movie director")
|
||||
|
||||
class MovieSchema(MovieBase):
|
||||
id: uuid.UUID
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
Loading…
x
Reference in New Issue
Block a user