Spaces:
Paused
Paused
Commit
·
8fd2be5
1
Parent(s):
f5263f9
change app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,7 @@ def load_songs():
|
|
| 12 |
try:
|
| 13 |
with open(json_path, "r", encoding="utf-8") as f:
|
| 14 |
songs_data = json.load(f)
|
|
|
|
| 15 |
except FileNotFoundError:
|
| 16 |
print("❌ songs.json not found!")
|
| 17 |
except json.JSONDecodeError:
|
|
@@ -22,21 +23,36 @@ def read_root():
|
|
| 22 |
return {"message": "Welcome to the Song API!"}
|
| 23 |
|
| 24 |
@app.get("/songs")
|
| 25 |
-
def get_songs(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
"""
|
| 27 |
-
Fetches a paginated list of songs.
|
| 28 |
:param page: The page number to retrieve (1-indexed).
|
| 29 |
:param limit: The maximum number of songs to return per page.
|
|
|
|
| 30 |
"""
|
| 31 |
if not songs_data:
|
| 32 |
return {"error": "No songs available. Check songs.json"}, 500
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
start_index = max((page - 1) * limit, 0)
|
| 35 |
end_index = start_index + limit
|
| 36 |
|
| 37 |
-
if start_index >= len(
|
| 38 |
-
return []
|
| 39 |
|
| 40 |
-
paginated_songs =
|
| 41 |
|
| 42 |
-
return paginated_songs
|
|
|
|
| 12 |
try:
|
| 13 |
with open(json_path, "r", encoding="utf-8") as f:
|
| 14 |
songs_data = json.load(f)
|
| 15 |
+
print(f"✅ Loaded {len(songs_data)} songs at startup.")
|
| 16 |
except FileNotFoundError:
|
| 17 |
print("❌ songs.json not found!")
|
| 18 |
except json.JSONDecodeError:
|
|
|
|
| 23 |
return {"message": "Welcome to the Song API!"}
|
| 24 |
|
| 25 |
@app.get("/songs")
|
| 26 |
+
def get_songs(
|
| 27 |
+
page: int = 1,
|
| 28 |
+
limit: int = 10,
|
| 29 |
+
query: str = Query(None, description="Search query for song title or artist") # Re-added query parameter
|
| 30 |
+
):
|
| 31 |
"""
|
| 32 |
+
Fetches a paginated and optionally filtered list of songs.
|
| 33 |
:param page: The page number to retrieve (1-indexed).
|
| 34 |
:param limit: The maximum number of songs to return per page.
|
| 35 |
+
:param query: Optional search string to filter by title or artist.
|
| 36 |
"""
|
| 37 |
if not songs_data:
|
| 38 |
return {"error": "No songs available. Check songs.json"}, 500
|
| 39 |
|
| 40 |
+
# Apply filtering first if a query is provided
|
| 41 |
+
filtered_songs = songs_data
|
| 42 |
+
if query:
|
| 43 |
+
search_query_lower = query.lower()
|
| 44 |
+
filtered_songs = [
|
| 45 |
+
song for song in songs_data
|
| 46 |
+
if search_query_lower in song.get("title", "").lower() or
|
| 47 |
+
search_query_lower in song.get("artist", "").lower()
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
start_index = max((page - 1) * limit, 0)
|
| 51 |
end_index = start_index + limit
|
| 52 |
|
| 53 |
+
if start_index >= len(filtered_songs):
|
| 54 |
+
return [] # No more songs to return for this query/page
|
| 55 |
|
| 56 |
+
paginated_songs = filtered_songs[start_index:end_index]
|
| 57 |
|
| 58 |
+
return paginated_songs
|