Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI | |
| from fastapi.responses import JSONResponse | |
| from duckduckgo_search import DDGS | |
| from fastapi.middleware.cors import CORSMiddleware | |
| # Initialize FastAPI app | |
| app = FastAPI() | |
| # CORS Middleware to allow cross-origin requests | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Allow all origins | |
| allow_credentials=True, | |
| allow_methods=["*"], # Allow all methods (GET, POST, etc.) | |
| allow_headers=["*"], # Allow all headers | |
| ) | |
| def home(): | |
| return {"message": "DuckDuckGo Search API is running!"} | |
| def search(query: str, max_results: int = 5): | |
| try: | |
| # Use headers to mimic a real browser | |
| headers = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0" | |
| } | |
| # Use DuckDuckGo Search API with HTML backend | |
| with DDGS(headers=headers) as ddgs: | |
| results = list(ddgs.text(query, max_results=max_results, backend="html")) | |
| return JSONResponse(content={"query": query, "results": results}) | |
| except Exception as e: | |
| return JSONResponse(content={"error": str(e)}, status_code=500) | |