Spaces:
Sleeping
Sleeping
Create api.py
Browse files
api.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Allow all origins (for testing — you can restrict later!)
|
| 9 |
+
app.add_middleware(
|
| 10 |
+
CORSMiddleware,
|
| 11 |
+
allow_origins=["*"], # ⚠️ In production, set to your trusted sites!
|
| 12 |
+
allow_credentials=True,
|
| 13 |
+
allow_methods=["*"],
|
| 14 |
+
allow_headers=["*"],
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Load your facts.csv
|
| 18 |
+
facts_df = pd.read_csv("facts.csv")
|
| 19 |
+
|
| 20 |
+
@app.get("/")
|
| 21 |
+
def home():
|
| 22 |
+
return {"message": "Fun Fact API is running!"}
|
| 23 |
+
|
| 24 |
+
@app.get("/api/random-fact")
|
| 25 |
+
def random_fact(category: str = "All"):
|
| 26 |
+
if category == "All":
|
| 27 |
+
pool = facts_df
|
| 28 |
+
else:
|
| 29 |
+
pool = facts_df[facts_df["category"].str.lower() == category.lower()]
|
| 30 |
+
if pool.empty:
|
| 31 |
+
return {"fact": "No facts found for this category."}
|
| 32 |
+
fact = pool.sample(1)["fact"].values[0]
|
| 33 |
+
return {"fact": fact}
|