-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelper.py
More file actions
55 lines (41 loc) · 1.39 KB
/
helper.py
File metadata and controls
55 lines (41 loc) · 1.39 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
import os
import requests
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("SERP_API_KEY")
if not api_key:
raise ValueError("SERP_API_KEY environment variable is not set.")
def get_serpapi_url(data):
"""
Constructs the SerpApi URL from the provided data.
Args:
data (dict): The data containing the SerpApi link.
Returns:
str: The complete SerpApi URL with the API key.
"""
if "serpapi_link" not in data:
raise ValueError("The provided data does not contain 'serpapi_link'.")
# Get the URL from the data
serpapi_url = data["serpapi_link"]
# Add API key to the URL if not already present
if "api_key=" not in serpapi_url:
separator = "&" if "?" in serpapi_url else "?"
serpapi_url = f"{serpapi_url}{separator}api_key={api_key}"
return serpapi_url
def get_data_from_serpapi(serpapi_url):
"""
Fetches data from the given SerpApi URL.
Args:
serpapi_url (str): The SerpApi URL to fetch data from.
Returns:
dict: The parsed JSON response from SerpApi.
Raises:
HTTPError: If the HTTP request returns an error status code.
"""
# Pass the API key as a parameter
params = {"api_key": api_key}
response = requests.get(serpapi_url, params=params)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()