File size: 1,164 Bytes
8422173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
# 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)