Using SdashAPI with Python
Python is widely used for backend development, data analysis, and building artificial intelligence applications. Integrating SdashAPI into your Python application is incredibly simple, especially when utilizing the popular requests library to handle HTTP communication.
Installing the Requests Library
2.2.1While Python comes with built-in libraries for making HTTP requests (like urllib), they can be overly complex and verbose. The industry standard for API integration in Python is the requests library.
If you do not already have it installed, open your terminal and install it via pip:
pip install requests
Writing the Python Script
2.2.2With the library installed, we can construct our GET request. We will define our API URL, pass our query parameters as a dictionary, and inject our API key into the headers dictionary.
Here is a complete example of fetching a JAMB Physics question in Python:
import requests
def fetch_past_question():
# Define the endpoint URL
url = "https://sdashapi.com/api/v1/q"
# Setup our query parameters
params = {
"type": "utme",
"subject": "physics"
}
# Configure the authentication headers
headers = {
"Accept": "application/json",
"AccessToken": "YOUR_API_KEY_HERE"
}
try:
# Send the GET request
response = requests.get(url, params=params, headers=headers)
# Raise an exception if the HTTP status code indicates an error
response.raise_for_status()
# Parse the JSON response into a Python dictionary
data = response.json()
if data.get('status') == 200:
question_data = data['data']
print(f"Question: {question_data['question']}")
print(f"Correct Answer: {question_data['answer'].upper()}")
print(f"Solution: {question_data['solution']}")
else:
print("API returned an unexpected status.")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
fetch_past_question()