Brave / main.py
Husnain Rasheed
Update main.py
075f035 verified
raw
history blame
2.2 kB
import httpx
from fastapi import FastAPI, HTTPException, Query
from typing import Optional
# Initialize the FastAPI app
app = FastAPI(
title="FastAPI DuckDuckGo Lite Proxy",
description="A FastAPI proxy for the DuckDuckGo Lite search engine.",
version="1.0.0",
)
# Define the base URL for the DuckDuckGo Lite API
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,
}
# Use httpx for asynchronous requests
async with httpx.AsyncClient() as client:
try:
# The OpenAPI spec indicates a POST, but parameters are in the query.
# A GET request is more appropriate for a search with query parameters.
response = await client.get(DUCKDUCKGO_LITE_URL, params=params)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
# Return the JSON response from the API
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)}",
)
# Optional: Add a root endpoint for health checks or basic info
@app.get("/", tags=["Root"])
async def read_root():
return {"message": "Welcome to the DuckDuckGo Lite API proxy!"}