API Calls Made Easy: Using Python to Access External Data
Ehab Henein
Data Executive with 20+ years of leadership experience creating business value through data
Introduction
APIs (Application Programming Interfaces) enable developers to access data and services from external sources. In this example, we will use Python to request the OpenFDA API and retrieve data about FDA-approved drugs. This process is commonly used in data science and software development to integrate external data into applications or analyses.
Setting Up Your Environment
Before we begin, please ensure you have Python installed on your system. You'll also need to install the requests library, which allows us to make HTTP requests in Python. To install Python in your environment, open your web browser and navigate to the official Python website.
?
You can install the requests library using pip:
pip install requests
Making an API Request
We'll start by making a simple GET request to the OpenFDA API to fetch information about a specific drug. The API endpoint we'll use is:
Let's write a Python script to perform this task:
import requests
import requests
def fetch_drug_data(drug_name):
# Define the base URL for the OpenFDA API
base_url = "https://api.fda.gov/drug/label.json"
# Set up the query parameters
params = {
'search': f'openfda.brand_name:"{drug_name}"',
'limit': 1 # Limit the results to 1 for demonstration purposes
}
# Make the API request
response = requests.get(base_url, params=params)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Check if results are available
if 'results' in data:
# Extract the relevant information
drug_info = data['results'][0]
print("Drug Name:", drug_info['openfda']['brand_name'][0])
print("Purpose:", drug_info.get('purpose', ['N/A'])[0])
print("Warnings:", drug_info.get('warnings', ['N/A'])[0])
else:
print("No results found for the specified drug.")
else:
print(f"Error: Unable to fetch data (Status Code: {response.status_code})")
# Example usage
fetch_drug_data("aspirin")
Understanding the Code
Once you run the code in your environment, you should see the following output:
Drug Name: Low Dose Aspirin Enteric Safety-Coated
Purpose: Purpose Pain reliever
Warnings: Warnings Reye's syndrome : Children and teenagers who have or are recovering from chicken pox or flu-like symptoms should not use this product. When using this product, if changes in behavior with nausea and vomiting occur, consult a doctor because these symptoms could be an early sign of Reye's ...
Further Exploration
For more complex applications, consider exploring additional features such as:
References