35 lines
952 B
Python
35 lines
952 B
Python
import requests
|
|
|
|
def get_joke():
|
|
try:
|
|
api_url = "https://icanhazdadjoke.com/"
|
|
|
|
# VERY IMPORTANT: request JSON response
|
|
headers = {
|
|
"Accept": "application/json",
|
|
"User-Agent": "python-script (learning requests)"
|
|
}
|
|
|
|
# Send GET request
|
|
response = requests.get(api_url, headers=headers)
|
|
|
|
if response.status_code == 200:
|
|
joke_data = response.json()
|
|
|
|
print("Joke:")
|
|
print(joke_data.get("joke", "No joke found."))
|
|
|
|
else:
|
|
print(f"Error: {response.status_code}")
|
|
print(response.text) # useful debugging
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
print(f"Network error: {e}")
|
|
except ValueError as e:
|
|
# This is the JSON decode error you were hitting
|
|
print("Server did not return valid JSON!")
|
|
print("Raw response was:")
|
|
print(response.text)
|
|
|
|
get_joke()
|
|
|