| import httpx |
| from fastapi import FastAPI, HTTPException, Query |
| from typing import Optional |
|
|
| |
| app = FastAPI( |
| title="FastAPI DuckDuckGo Lite Proxy", |
| description="A FastAPI proxy for the DuckDuckGo Lite search engine.", |
| version="1.0.0", |
| ) |
|
|
| |
| DUCKDUCKGO_LITE_URL = "https://lite.duckduckgo.com/lite/" |
|
|
| @app.get("/search", tags=["Search"]) |
| async def search_duckduckgo( |
| q: str = Query(..., description="The search query."), |
| s: Optional[int] = Query(0, description="Can be `0`."), |
| o: Optional[str] = Query("json", description="Set to `json` for JSON output."), |
| kl: Optional[str] = Query("wt-wt", description="Region, e.g., us-en, uk-en."), |
| bing_market: Optional[str] = Query("wt-wt", description="Bing market region.") |
| ): |
| """ |
| Performs a search using the DuckDuckGo Lite API and returns the results. |
| """ |
| params = { |
| "q": q, |
| "s": s, |
| "o": o, |
| "kl": kl, |
| "bing_market": bing_market, |
| } |
|
|
| |
| async with httpx.AsyncClient() as client: |
| try: |
| |
| |
| response = await client.get(DUCKDUCKGO_LITE_URL, params=params) |
| |
| |
| response.raise_for_status() |
| |
| |
| return response.json() |
|
|
| except httpx.HTTPStatusError as e: |
| raise HTTPException( |
| status_code=e.response.status_code, |
| detail=f"Error from DuckDuckGo API: {e.response.text}", |
| ) |
| except httpx.RequestError as e: |
| raise HTTPException( |
| status_code=500, |
| detail=f"Failed to connect to DuckDuckGo API: {str(e)}", |
| ) |
|
|
| |
| @app.get("/", tags=["Root"]) |
| async def read_root(): |
| return {"message": "Welcome to the DuckDuckGo Lite API proxy!"} |