Husnain Rasheed commited on
Commit
529d4ca
·
verified ·
1 Parent(s): b8855ef

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +22 -20
main.py CHANGED
@@ -1,49 +1,52 @@
1
  import httpx
 
2
  from fastapi import FastAPI, HTTPException, Query
3
  from typing import Optional
4
 
5
  # Initialize the FastAPI app
6
  app = FastAPI(
7
- title="FastAPI DuckDuckGo Lite Proxy",
8
- description="A FastAPI proxy for the DuckDuckGo Lite search engine.",
9
  version="1.0.0",
10
  )
11
 
12
- # Define the base URL for the DuckDuckGo Lite API
13
- DUCKDUCKGO_LITE_URL = "https://lite.duckduckgo.com/lite/"
14
 
15
  @app.get("/search", tags=["Search"])
16
  async def search_duckduckgo(
17
  q: str = Query(..., description="The search query."),
18
- s: Optional[int] = Query(0, description="Can be `0`."),
19
- o: Optional[str] = Query("json", description="Set to `json` for JSON output."),
20
- kl: Optional[str] = Query("wt-wt", description="Region, e.g., us-en, uk-en."),
21
- bing_market: Optional[str] = Query("wt-wt", description="Bing market region.")
22
  ):
23
  """
24
- Performs a search using the DuckDuckGo Lite API and returns the results.
25
  """
26
  params = {
27
  "q": q,
28
- "s": s,
29
- "o": o,
30
- "kl": kl,
31
- "bing_market": bing_market,
32
  }
33
 
34
- # Use httpx for asynchronous requests
35
  async with httpx.AsyncClient() as client:
36
  try:
37
- # The OpenAPI spec indicates a POST, but parameters are in the query.
38
- # A GET request is more appropriate for a search with query parameters.
39
- response = await client.get(DUCKDUCKGO_LITE_URL, params=params)
40
 
41
  # Raise an exception for bad status codes (4xx or 5xx)
42
  response.raise_for_status()
43
 
44
- # Return the JSON response from the API
 
 
 
 
 
45
  return response.json()
46
 
 
 
 
 
 
 
47
  except httpx.HTTPStatusError as e:
48
  raise HTTPException(
49
  status_code=e.response.status_code,
@@ -55,7 +58,6 @@ async def search_duckduckgo(
55
  detail=f"Failed to connect to DuckDuckGo API: {str(e)}",
56
  )
57
 
58
- # Optional: Add a root endpoint for health checks or basic info
59
  @app.get("/", tags=["Root"])
60
  async def read_root():
61
- return {"message": "Welcome to the DuckDuckGo Lite API proxy!"}
 
1
  import httpx
2
+ import json
3
  from fastapi import FastAPI, HTTPException, Query
4
  from typing import Optional
5
 
6
  # Initialize the FastAPI app
7
  app = FastAPI(
8
+ title="FastAPI DuckDuckGo API Proxy",
9
+ description="A FastAPI proxy for the DuckDuckGo Instant Answer API.",
10
  version="1.0.0",
11
  )
12
 
13
+ # Define the base URL for the DuckDuckGo Instant Answer API (for JSON results)
14
+ DUCKDUCKGO_API_URL = "https://api.duckduckgo.com/"
15
 
16
  @app.get("/search", tags=["Search"])
17
  async def search_duckduckgo(
18
  q: str = Query(..., description="The search query."),
 
 
 
 
19
  ):
20
  """
21
+ Performs a search using the DuckDuckGo Instant Answer API and returns the results in JSON format.
22
  """
23
  params = {
24
  "q": q,
25
+ "format": "json", # Request JSON format
26
+ "no_html": 1, # Disable HTML in the response
 
 
27
  }
28
 
 
29
  async with httpx.AsyncClient() as client:
30
  try:
31
+ response = await client.get(DUCKDUCKGO_API_URL, params=params)
 
 
32
 
33
  # Raise an exception for bad status codes (4xx or 5xx)
34
  response.raise_for_status()
35
 
36
+ # The API returns an empty string for no results, which is not valid JSON.
37
+ # Handle this case explicitly.
38
+ if not response.text:
39
+ return {"results": [], "message": "No results found."}
40
+
41
+ # Attempt to parse the JSON response
42
  return response.json()
43
 
44
+ except json.JSONDecodeError:
45
+ # If the response is not valid JSON, raise an internal server error
46
+ raise HTTPException(
47
+ status_code=500,
48
+ detail=f"Failed to decode JSON from DuckDuckGo API. Response text: {response.text}",
49
+ )
50
  except httpx.HTTPStatusError as e:
51
  raise HTTPException(
52
  status_code=e.response.status_code,
 
58
  detail=f"Failed to connect to DuckDuckGo API: {str(e)}",
59
  )
60
 
 
61
  @app.get("/", tags=["Root"])
62
  async def read_root():
63
+ return {"message": "Welcome to the DuckDuckGo API proxy!"}