I am creating an API to read from a BigQuery table and write to another Bigquery table using FastAPI. I am able to read data in the response but unable to write data. The second function shows an error. What is wrong there. Here is my code:
@app.get(“/bigquery_data”, response_model=List[dict])
async def get_bigquery_data():
try:
dataset_id = “soy-lore-422902-a3.Test”
table_name = “hello”
sql_query = f"SELECT Index, City FROM `{dataset_id}.{table_name}`;"
query_job = bq_client.query(sql_query)
results = query_job.result()
data = [{"Index": row.Index, "City": row.City} for row in results]
return data
@app.post(“/post_to_bigquery”, response_model=get_bigquery_data)
async def post_to_bigquery(user: get_bigquery_data):
try:
data_to_insert = [{“Index”: get_bigquery_data.Index, “City”: get_bigquery_data.City}]
dataset_id = “soy-lore-422902-a3.Test”
table_name = “test”
table_ref = bq_client.dataset(dataset_id).table(table_name)
table = bq_client.get_table(table_ref)
bq_client.insert_rows(table, data_to_insert)