Spaces:
Running
Running
from fastapi import FastAPI, Query | |
import json | |
import os | |
app = FastAPI() | |
songs_data = [] # Cached in-memory list of songs | |
def load_songs(): | |
global songs_data | |
json_path = os.path.join(os.path.dirname(__file__), "songs.json") | |
try: | |
with open(json_path, "r", encoding="utf-8") as f: | |
songs_data = json.load(f) | |
print(f"β Loaded {len(songs_data)} songs at startup.") | |
except FileNotFoundError: | |
print("β songs.json not found!") | |
except json.JSONDecodeError: | |
print("β Error decoding songs.json!") | |
def read_root(): | |
return {"message": "Welcome to the Song API!"} | |
def get_songs( | |
page: int = 1, | |
limit: int = 5, | |
query: str = Query(None, description="Search query for song title or artist") # Re-added query parameter | |
): | |
""" | |
Fetches a paginated and optionally filtered list of songs. | |
:param page: The page number to retrieve (1-indexed). | |
:param limit: The maximum number of songs to return per page. | |
:param query: Optional search string to filter by title or artist. | |
""" | |
if not songs_data: | |
return {"error": "No songs available. Check songs.json"}, 500 | |
# Apply filtering first if a query is provided | |
filtered_songs = songs_data | |
if query: | |
search_query_lower = query.lower() | |
filtered_songs = [ | |
song for song in songs_data | |
if search_query_lower in song.get("title", "").lower() or | |
search_query_lower in song.get("artist", "").lower() | |
] | |
start_index = max((page - 1) * limit, 0) | |
end_index = start_index + limit | |
if start_index >= len(filtered_songs): | |
return [] # No more songs to return for this query/page | |
paginated_songs = filtered_songs[start_index:end_index] | |
return paginated_songs |