fact-api / api.py
ibrahim321123's picture
Create api.py
603ed7a verified
raw
history blame contribute delete
884 Bytes
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
import random
app = FastAPI()
# Allow all origins (for testing — you can restrict later!)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # ⚠️ In production, set to your trusted sites!
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load your facts.csv
facts_df = pd.read_csv("facts.csv")
@app.get("/")
def home():
return {"message": "Fun Fact API is running!"}
@app.get("/api/random-fact")
def random_fact(category: str = "All"):
if category == "All":
pool = facts_df
else:
pool = facts_df[facts_df["category"].str.lower() == category.lower()]
if pool.empty:
return {"fact": "No facts found for this category."}
fact = pool.sample(1)["fact"].values[0]
return {"fact": fact}