Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Need Help - How to Use Cloud Functions to Retrieve API Data and Store It in a Cloud Bucket

Hi, I need help on below issue.
I ran below code in Cloud Function successfully, but I encountered an issue where the code executed without errors, yet no data appeared in the cloud bucket. Can you please help me identify the problem? Thank you.

import requests
import pandas as pd
from google.cloud import storage

def extract_exchange_rate(request):
start_date = request.args.get('start_date', '1997-01-01') 
end_date = request.args.get('end_date', '2023-12-31') 


bucket_name = 'your_bucket_name'
file_name = f'bnm-exchange-rate-{start_date}_{end_date}.csv'

headers = {'Accept': 'application/vnd.BNM.API.v1+json'}
parameters = {'session': '1700', 'quote': 'rm'}

dfs = []

urls = [f'https://api.bnm.gov.my/public/exchange-rate/SGD/year/{year}/month/{month}',
f'https://api.bnm.gov.my/public/exchange-rate/THB/year/{year}/month/{month}',
f'https://api.bnm.gov.my/public/exchange-rate/PHP/year/{year}/month/{month}',
f'https://api.bnm.gov.my/public/exchange-rate/GBP/year/{year}/month/{month}',
f'https://api.bnm.gov.my/public/exchange-rate/USD/year/{year}/month/{month}',
f'https://api.bnm.gov.my/public/exchange-rate/AUD/year/{year}/month/{month}',
f'https://api.bnm.gov.my/public/exchange-rate/IDR/year/{year}/month/{month}']

for url in urls:
response = requests.get(url, headers=headers, params=parameters)
data = response.json()
data2 = data['data']['rate'][-1]
data2['currency_code'] = data['data']['currency_code']
dfs.append(data2)

df = pd.DataFrame(dfs)

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(file_name)
df.to_csv('/tmp/' + file_name, index=False)
blob.upload_from_filename('/tmp/' + file_name)

return f'Data saved to Cloud Storage: gs://{bucket_name}/{file_name}'

1 1 643
1 REPLY 1
Top Labels in this Space