the-emergent-show / image_api.py
inventwithdean
add dynamic cameras and youtube chat
7b58f25
raw
history blame contribute delete
756 Bytes
import requests
from dotenv import load_dotenv
import os
load_dotenv()
base_url = "https://api.pexels.com/v1"
api_key = os.getenv("API_KEY_PEXELS")
def get_random_image(topic: str) -> tuple[str, str] | tuple[None, None]:
# Returns the url of a random image on a topic
params = {"query": topic, "per_page": 1}
headers = {"Authorization": api_key}
response = requests.get(url=f"{base_url}/search", params=params, headers=headers)
response_json = response.json()
if response.status_code != 200:
return None, None
try:
photo = response_json["photos"][0]
landscape_url = photo["src"]["landscape"]
alt = photo["alt"]
except:
landscape_url, alt = None, None
return landscape_url, alt