Back

StarWars API

The code retrieves data from a given API endpoint and prints the names of the items returned.

Code Block

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 Code

Code Analysis

Handling Different Data Structures:

  • The SWAPI may return different structures based on the endpoint (e.g., "people", "planets", "films"). To handle this, you should check if the data contains the expected keys before attempting to access them.

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:

  • Currently, the code only handles HTTP errors. You should also handle other exceptions, such as network issues or invalid responses.

except requests.RequestException as e:
   print(f"An error occurred: {e}")
   return None

Input Validation:

  • Validate user input to ensure it's a valid option before making the API request. This can prevent unnecessary requests to the API and provide better user feedback.

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:

  • Refactor the code to make it more modular and readable. For instance, separate input handling and output processing into different 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:

  • Provide more detailed user feedback and documentation to improve the usability of the script. For example, explain what each valid option represents and how it affects the data retrieved.

Consider API Rate Limits:

  • If the API has rate limits, consider adding rate-limiting logic to avoid hitting those limits, especially if this script is part of a larger application.

Final Notes:

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.