I need help in python code to pull data from the FDA drugs api (https://open.fda.gov/apis/drug/drugsfda/) and write it to a csv so I can manipulate it on tableau.
import requests
import csv
def fetch_drugs_from_fda(api_key):
url = "https://api.fda.gov/drug/drugsfda.json"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise exception for 4xx or 5xx status codes
data = response.json()
results = data.get("results")
if not results:
print("No results found in API response.")
return results
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
except Exception as e:
print(f"An error occurred: {e}")
return None
def save_drugs_to_csv(drugs):
if drugs is None:
return
with open("fda_drugs.csv", "w", newline="", encoding="utf-8") as csvfile:
fieldnames = ["brand_name", "generic_name", "manufacturer_name", "product_ndc"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for drug in drugs:
writer.writerow({
"brand_name": drug.get("brand_name"),
"generic_name": drug.get("generic_name"),
"manufacturer_name": drug.get("manufacturer_name"),
"product_ndc": drug.get("product_ndc")
})
print("Data saved successfully to fda_drugs.csv")
if __name__ == "__main__":
api_key = "my_key" actual API key
drugs = fetch_drugs_from_fda(api_key)
if drugs:
save_drugs_to_csv(drugs)
else:
print("Failed to fetch drugs from FDA API.")
Im extremely new to this and have never used API’s before i need the csv to make visualisations and the one for FDA is very confusing for me
New contributor
Satwick Awasthi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1