You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from fastapi import Depends, FastAPI
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.db import get_session, init_db
|
|
from app.models import Song, SongCreate
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
# REMOVED BECAUSE WE NOW USE ALEMBIC TO CREATE AND MANAGE TABLES
|
|
# @app.on_event("startup")
|
|
# async def on_startup():
|
|
# """
|
|
# It's worth noting that from app.models import Song is required.
|
|
# Without it, the song table will not be created. Kind of like
|
|
# how I have to do my flask sql alchemy models
|
|
# """
|
|
# await init_db()
|
|
|
|
|
|
@app.get("/ping")
|
|
async def pong():
|
|
return {"ping": "pong!"}
|
|
|
|
|
|
@app.get("/songs", response_model=list[Song])
|
|
async def get_songs(session: AsyncSession = Depends(get_session)):
|
|
result = await session.execute(select(Song))
|
|
songs = result.scalars().all()
|
|
return [Song(name=song.name, artist=song.artist, id=song.id, year=song.year) for song in songs]
|
|
|
|
|
|
@app.post("/songs")
|
|
async def add_song(song: SongCreate, session: AsyncSession = Depends(get_session)):
|
|
song = Song(name=song.name, artist=song.artist, year=song.year)
|
|
session.add(song)
|
|
await session.commit()
|
|
await session.refresh(song) # refreshed becuase of the async nature
|
|
return song
|