File size: 1,854 Bytes
e680609
ce015b1
 
4929f3f
ce015b1
e680609
 
 
 
 
 
 
 
 
8fd2be5
e680609
 
 
 
4929f3f
 
bbd2266
ce015b1
bbd2266
 
8fd2be5
 
5818f30
8fd2be5
 
e680609
8fd2be5
e680609
 
8fd2be5
e680609
 
 
 
8fd2be5
 
 
 
 
 
 
 
 
 
e680609
 
 
8fd2be5
 
e680609
8fd2be5
e680609
8fd2be5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from fastapi import FastAPI, Query
import json
import os

app = FastAPI()
songs_data = []  # Cached in-memory list of songs

@app.on_event("startup")
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!")

@app.get("/")
def read_root():
    return {"message": "Welcome to the Song API!"}

@app.get("/songs")
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