Pydantic v2 Schemas
Relevant source files
The following files were used as context for generating this wiki page:
Pydantic v2 schemas serve as the foundational data validation and serialization layer for the MoodTune backend. These schemas define the structure of request bodies, response payloads, and internal data transfers between the API layer and services. By leveraging Pydantic v2 features like ConfigDict and model_config, the project ensures type safety and consistency across Spotify integrations, audio file analysis, and user history retrieval.
The schemas are organized logically within the app/schemas/ directory, with specific modules handling different domains such as playlist analysis, raw audio feature extraction, and Spotify OAuth status. This structure allows the FastAPI application to automatically generate OpenAPI documentation and perform runtime validation of all incoming and outgoing data.
Sources: app/schemas/init.py:1, CLAUDE.md:27-28, CLAUDE.md:73-80
Implementation Patterns
MoodTune utilizes Pydantic v2's updated syntax for model configuration. The project standardizes on using ConfigDict or the model_config attribute to enable ORM-like compatibility with database results (Supabase Postgres) via from_attributes=True.
from pydantic import BaseModel, ConfigDict
class MyResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: str
name: str
Sources: CLAUDE.md:73-80, app/schemas/analysis.py:68-69
Playlist Analysis Schemas
The analysis schemas define the complex nested structure of mood results calculated from Spotify audio features. This includes statistical distributions of moods, averaged audio features, and representative "top tracks" for a given playlist.
Relationship Diagram: Analysis Results
The following diagram illustrates how individual track metrics aggregate into a comprehensive MoodResult.
Sources: app/schemas/analysis.py:10-58
Summary Table: Analysis Data Fields
| Class | Field | Type | Description |
|---|---|---|---|
MoodDistribution | happy | float | Tracks with valence >= 0.6 |
MoodDistribution | sad | float | Tracks with valence < 0.4 |
MoodResult | primary_mood | str | The dominant mood category (e.g., "upbeat") |
MoodResult | confidence | float | Certainty score of the classification |
PlaylistAnalysisResponse | id | UUID | Unique identifier for the saved analysis |
Sources: app/schemas/analysis.py:24-30, app/schemas/analysis.py:44-53, app/schemas/analysis.py:63-67
Audio Analysis and Upload Schemas
For direct audio processing via librosa, MoodTune uses specialized schemas to handle file metadata and granular audio features such as spectral centroids and zero-crossing rates.
Data Flow: Audio Processing
This flow shows the transformation of an upload request into a complete analysis response.
Sources: app/schemas/audio_analysis.py:7-70
Key Audio Schema Components
- AudioFeatures: Captures technical metrics like
spectral_centroid(Brightness),rms_energy(Loudness), andharmonic_ratio. It also includes UI-friendly labels likeenergy_label. - MoodFromAudio: Extends the raw features with AI-inferred data, including a
reasoningstring explaining the mood choice and aconfidencescore bounded between 0.0 and 1.0.
Sources: app/schemas/audio_analysis.py:16-41, app/schemas/audio_analysis.py:44-53
Spotify Integration Schemas
These schemas manage the state of Spotify OAuth connections and the structure of data retrieved from the Spotify Web API.
Spotify Schema Definitions
| Schema | Purpose | Key Fields |
|---|---|---|
SpotifyStatusResponse | Connection check | connected (bool), spotify_user_id (Optional str) |
SpotifyPlaylist | Catalog representation | id, name, tracks_count, image_url |
SpotifyConnectionCreate | Token persistence | access_token, refresh_token, expires_at |
SpotifyProfile | User info | display_name, email, playlists_count |
Sources: app/schemas/spotify.py:10-23, app/schemas/spotify.py:31-38, app/schemas/spotify.py:46-54
Core Configuration Schema
The application settings are managed by pydantic-settings, allowing for environment-variable-driven configuration with validation.
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
# Audio upload settings
MAX_UPLOAD_SIZE_MB: int = 15
ALLOWED_AUDIO_FORMATS: List[str] = ["mp3", "m4a", "flac", "wav", "ogg"]
TEMP_AUDIO_DIR: str = "/tmp/moodtune-audio"
Sources: app/core/config.py:27-77
Summary
Pydantic v2 schemas in MoodTune enforce a strict contract between the frontend and backend. By defining clear models for both Spotify-sourced data and librosa audio analysis results, the system maintains high data integrity. The use of Pydantic's validation features ensures that complex calculations, such as mood distributions and audio confidence scores, are always delivered in the expected format to the client.