Chatbot / app /search.py
ShadowTEM's picture
uploaded the rest
8422173 verified
Raw
History Blame Contribute Delete
1.16 kB
# search.py
import requests
def search_query(query):
"""
Perform a search using the DuckDuckGo Instant Answer API.
Parameters:
query (str): The search query.
Returns:
dict: A dictionary with the JSON response from the API.
Raises:
Exception: If the API call fails.
"""
url = "https://api.duckduckgo.com/"
params = {
"q": query,
"format": "json",
"no_html": 1,
"skip_disambig": 1
}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Search API error: {response.status_code}")
if __name__ == "__main__":
# Example usage:
query = "latest cancer research news"
try:
results = search_query(query)
# Print the title and abstract (if available) from the response.
# DuckDuckGo Instant Answer API returns a variety of keys depending on the query.
print("Search Results:")
print(results)
except Exception as e:
print("Error during search:", e)