-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetchapi.py
More file actions
56 lines (35 loc) · 1.36 KB
/
Copy pathfetchapi.py
File metadata and controls
56 lines (35 loc) · 1.36 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import requests
import json
import os
from google.cloud import storage
def fetch_product_data():
url = "https://fakestoreapi.com/products"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
return data #returns list of products found in the json file
else:
raise Exception(f"Error fetching data: {response.status_code}")
def save_data_locally(data, filename ="products.json") :
with open(filename, "w") as file:
json.dump(data, file, indent =4)
print(f"Data saved locally in this file {filename}")
def upload_to_gcs(bucket_name, source_file, destination_blob):
client = storage.Client()
bucket = client.bucket(bucket_name)
blob = bucket.blob(destination_blob)
blob.upload_from_filename(source_file)
print(f"File {source_file} uploaded to {bucket_name}/{destination_blob}")
def main() :
#fecth the data
data = fetch_product_data()
# save the data locally in the file "products.json"
filename= "products.json"
save_data_locally(data, filename)
#upload data to the google cloud storage in the specific bucket
bucket_name = "fake-store-data-bucket"
destination_blob = "products/products.json"
upload_to_gcs(bucket_name, filename, destination_blob)
if __name__ == "__main__":
main()