簡體   English   中英

Airflow:如何將數據從 REST API 加載到 BigQuery?

[英]Airflow: How to load data from a REST API to BigQuery?

我是 Airflow 的新手,我正在嘗試編寫一個 Python 方法將數據從 REST API 插入 BigQuery,但我沒有運氣。

到目前為止,我已經嘗試閱讀文檔,但還沒有找到我想要完成的示例; 雖然,我寫了下面的代碼,但我不確定它是否正確:

def insert_from_api_to_bq():
    
    request1 = Request(
        '[URL GOES GERE]', headers=headers)

    sale_list = urlopen(request1).read()
    dec_sale_list = json.loads(sale_list)
    for sale in dec_sale_list['SaleList']:
        print("sale ID: " + sale['SaleID'] + " Customer:" + sale['Customer'] + " Order Date: " + sale['OrderDate'])

with DAG("sales_data_pipeline", start_date=datetime(2021, 1 ,1),
    schedule_interval="@daily", default_args=default_args, catchup=False) as dag:

    downloading_sales = PythonOperator(
        task_id="downloading_sales",
        python_callable=download_sales

你的方向很好。

在從 api 檢索數據的Python方法中,您可以使用Python客戶端將結果轉換並加載到BigQuery表中:

from google.cloud import bigquery

def insert_from_api_to_bq():
    
    request1 = Request(
        '[URL GOES GERE]', headers=headers)

    sale_list = urlopen(request1).read()
    dec_sale_list = json.loads(sale_list)
    
    # you can transform and adapt dec_sale_list before writing to BQ
    client = bigquery.Client()
    client.insert_rows_json(f'{dataset}.{table}', dec_sale_list)

with DAG("sales_data_pipeline", start_date=datetime(2021, 1 ,1),
    schedule_interval="@daily", default_args=default_args, catchup=False) as dag:

    downloading_sales = PythonOperator(
        task_id="downloading_sales",
        python_callable=download_sales

insert_rows_json方法允許將DictPython列表保存到BigQuery

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM