File size: 1,196 Bytes
3809b9b
 
11ee355
3809b9b
10da29a
3809b9b
10da29a
 
3809b9b
11ee355
 
3809b9b
11ee355
3809b9b
 
11ee355
10da29a
d3ff814
 
 
 
11ee355
3809b9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3ff814
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
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
)

@app.get("/")
def home():
    return {"message": "DuckDuckGo Search API is running!"}

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