niharika17032001 commited on
Commit
e680609
·
1 Parent(s): cb0c780

Create Dockerfile

Browse files
Files changed (1) hide show
  1. app.py +32 -6
app.py CHANGED
@@ -1,16 +1,42 @@
1
- from fastapi import FastAPI
2
  import json
3
  import os
4
 
5
  app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  @app.get("/")
8
  def read_root():
9
  return {"message": "Welcome to the Song API!"}
10
 
11
  @app.get("/songs")
12
- def get_songs():
13
- json_path = os.path.join(os.path.dirname(__file__), "songs.json")
14
- with open(json_path, "r", encoding="utf-8") as f:
15
- songs = json.load(f)
16
- return songs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Query
2
  import json
3
  import os
4
 
5
  app = FastAPI()
6
+ songs_data = [] # Cached in-memory list of songs
7
+
8
+ @app.on_event("startup")
9
+ def load_songs():
10
+ global songs_data
11
+ json_path = os.path.join(os.path.dirname(__file__), "songs.json")
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:
18
+ print("❌ Error decoding songs.json!")
19
 
20
  @app.get("/")
21
  def read_root():
22
  return {"message": "Welcome to the Song API!"}
23
 
24
  @app.get("/songs")
25
+ def get_songs(page: int = 1, limit: int = 10):
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(songs_data):
38
+ return []
39
+
40
+ paginated_songs = songs_data[start_index:end_index]
41
+
42
+ return paginated_songs