import requests
import json
def get_cow_joke():
"""
Fetches a joke about cows from a public API.
Returns:
A string containing the joke, or an error message if the API request fails.
"""
api_url = "https://v2.jokeapi.dev/joke/Programming,Animal?blacklistFlags=nsfw,racist,sexist,explicit&safe-mode" # Using JokeAPI
try:
response = requests.get(api_url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
data = response.json()
if data["type"] == "single":
return data["joke"]
elif data["type"] == "twopart":
return f"{data['setup']}\n{data['delivery']}"
else:
return "Sorry, I couldn't fetch a cow joke right now. The API returned an unexpected response."
except requests.exceptions.RequestException as e:
return f"Error fetching joke: {e}"
except json.JSONDecodeError as e:
return f"Error decoding JSON response: {e}"
if __name__ == "__main__":
joke = get_cow_joke()
print(joke)
Key improvements and explanations:
- Error Handling: Crucially includes
try...except blocks to handle potential errors:
requests.exceptions.RequestException: Catches network errors (e.g., no internet connection, API server down).
json.JSONDecodeError: Catches errors if the API returns something that isn't valid JSON.
response.raise_for_status(): This is very important. It checks the HTTP status code of the response. If the status code indicates an error (4xx or 5xx), it raises an HTTPError, which is caught by the requests.exceptions.RequestException block. This makes the program much more robust.
- API Choice (JokeAPI): Uses the JokeAPI (https://v2.jokeapi.dev/) which is a reliable and free API for jokes. It's specifically chosen because it's easy to use and provides a good structure for different joke types.
- Joke Type Handling: The API can return either a "single" joke or a "twopart" joke (setup and delivery). The code now correctly handles both cases.
- Blacklist Flags: Includes
blacklistFlags=nsfw,racist,sexist,explicit&safe-mode in the API URL. This helps ensure that the jokes are appropriate and avoids offensive content. The safe-mode flag is important for filtering potentially problematic jokes.
- Clearer Return Values: Returns informative error messages if something goes wrong, instead of just crashing.
if __name__ == "__main__": block: This ensures that the get_cow_joke() function is only called when the script is run directly (not when it's imported as a module). This is standard practice in Python.
- Comments: Includes comments to explain what the code is doing.
- Concise and Readable: The code is formatted for readability.
How to run the code:
-
Install requests: If you don't have it already, install the requests library:
pip install requests
-
Save the code: Save the code as a Python file (e.g., cow_joke.py).
-
Run the file:
python cow_joke.py
The program will then fetch a cow joke from the API and print it to the console. If there's an error, it will print an error message.