Creating a Bigquery table by Python API

11,844

Solution 1

You're getting back a TableReference object, not a Table on your 2nd last line (table = dataset.table("mytable")). You need to do this:

[..]
table_ref = dataset.table('my_table')
table = bigquery.Table(table_ref, schema=SCHEMA)
table = client.create_table(table)
[..]

See here.

Solution 2

Similar answer, with an example of schema and another source

from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client()

# TODO(developer): Set table_id to the ID of the table to create.
# table_id = "your-project.your_dataset.your_table_name"

schema = [
    bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"),
    bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"),
]

table = bigquery.Table(table_id, schema=schema)
table = client.create_table(table)  # Make an API request.
print(
    "Created table {}.{}.{}".format(table.project, table.dataset_id, table.table_id)
)
Share:
11,844

Related videos on Youtube

MFR
Author by

MFR

Doing stuff with data

Updated on September 29, 2022

Comments

  • MFR
    MFR about 1 year

    I'm trying to create a Bigquery table using Python API.

    from google.cloud import bigquery
    
    bigquery_client = bigquery.Client(project="myproject")
    dataset = bigquery_client.dataset("mydataset")
    
    table = dataset.table("mytable")
    table.create()
    

    I keep getting this error

    AttributeError: 'TableReference' object has no attribute 'create'

    Does anyone have any idea?