File size: 1,360 Bytes
2e13a13 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import requests
import json
import os
import re
def fetch_drug_label(drug_name):
"""
Fetch FDA drug label information for the given drug name from the FDA Open Data API
and save it as a JSON file in the 'data/' folder.
"""
url = f'https://api.fda.gov/drug/label.json?search=openfda.brand_name:"{drug_name}"&limit=1'
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for HTTP issues
data = response.json()
if 'results' in data and data.get('results'):
result = data['results'][0] # Use the first result
# Create a safe filename for the drug
safe_drug_name = re.sub(r'\W+', '_', drug_name.lower())
os.makedirs("data", exist_ok=True)
json_file_path = f"data/{safe_drug_name}_label.json"
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(result, json_file, indent=4, ensure_ascii=False)
print(f"Drug label information saved for {drug_name} ({json_file_path})")
return json_file_path
else:
print(f"No data found for {drug_name}.")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching data for {drug_name}: {e}")
return None
|