StarWars API
The code retrieves data from a given API endpoint and prints the names of the items returned.
The code retrieves data from a given API endpoint and prints the names of the items returned.
The script prompts the user to specify which type of data they want to explore (e.g., "people", "planets") from the SWAPI (Star Wars API). It then constructs the appropriate URL and fetches the data using the requests library. If the request is successful, it processes the JSON response and prints the names of the items. If the request fails, it handles the error and informs the user that data retrieval was unsuccessful.
Check out the CodeHandling Different Data Structures:
if 'results' in data:
for item in data['results']:
print(item.get("name", "No name available"))
else:
print("Unexpected data structure received.")
Improved Error Handling:
except requests.RequestException as e:
print(f"An error occurred: {e}")
return None
Input Validation:
valid_options = ["people", "planets", "films", "species", "vehicles", "starships"]
if option not in valid_options:
print("Invalid option. Please choose from:", ", ".join(valid_options))
exit()
Refactor Code into Functions:
def get_option():
valid_options = ["people", "planets", "films", "species", "vehicles", "starships"]
option = input("What data would you like to explore?").strip().lower()
if option not in valid_options:
print("Invalid option. Please choose from:", ", ".join(valid_options))
exit()
return option
def display_data(data):
if 'results' in data:
for item in data['results']:
print(item.get("name", "No name available"))
else:
print("Unexpected data structure received.")
option = get_option()
data = fetch_data(option)
if data:
display_data(data)
else:
print("Unable to download data")
User Feedback and Documentation:
Consider API Rate Limits:
This code effectively demonstrates basic API interaction and error handling. By improving data structure handling, enhancing error management, validating inputs, and modularizing the code, you can make the script more robust and user-friendly. This approach will help in better handling of different API responses and providing a smoother experience for the users.