2025-03-25 16:18:07 +01:00

69 lines
2.4 KiB
Python

Sure, here's an example of a FastAPI endpoint that adds music and artist to the database using SQLAlchemy models and Pydantic schemas:
```python
from typing import List
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from database import get_db
from models import Music, Artist
from schemas import MusicCreate, ArtistCreate
from app.api.models.music_model import *
from app.api.schemas.music_schema import *
router = APIRouter()
# SQLAlchemy models
@router.post("/music", response_model=List[MusicCreate])
def create_music(musics: List[MusicCreate], artists: List[ArtistCreate], db: Session = Depends(get_db)):
db_artists = [Artist(name=artist.name) for artist in artists]
db.add_all(db_artists)
db.commit()
db.refresh(db_artists)
db_musics = [Music(title=music.title, artist_id=db_artists[music.artist_id - 1].id) for music in musics]
db.add_all(db_musics)
db.commit()
db.refresh(db_musics)
return [MusicCreate(title=music.title, artist_id=music.artist_id) for music in db_musics]
```
Here's a breakdown of the code:
1. We import the necessary modules and dependencies.
2. We define the `Music` and `Artist` SQLAlchemy models with a one-to-many relationship.
3. We define the `MusicCreate` and `ArtistCreate` Pydantic schemas for data validation and serialization.
4. We create a FastAPI router with a `POST` endpoint at `/music`.
5. The `create_music` function takes two lists of `MusicCreate` and `ArtistCreate` objects, as well as a database session (`db`).
6. We create `Artist` objects from the `ArtistCreate` objects and add them to the database.
7. We create `Music` objects from the `MusicCreate` objects, associating them with the appropriate `Artist` objects based on the `artist_id`.
8. We add the `Music` objects to the database and commit the changes.
9. We return a list of `MusicCreate` objects representing the newly created music entries.
To use this endpoint, you would send a POST request to `/music` with a JSON payload containing lists of `MusicCreate` and `ArtistCreate` objects, for example:
```json
{
"musics": [
{
"title": "Song 1",
"artist_id": 1
},
{
"title": "Song 2",
"artist_id": 2
}
],
"artists": [
{
"name": "Artist 1"
},
{
"name": "Artist 2"
}
]
}
```
This would create two new artists and two new music entries associated with those artists in the database.