Search code examples
python-3.xnotion-apinotion

Create a table using Notion API


I'm trying to figure out how to use Notion API, but following example in their official documentation return an ungooglable error.

I'm following this docs

and here is my code:

headers = {
    'Authorization': f"Bearer {api_key}",
    "accept": "application/json",
    'Content-Type': 'application/json',
    'Notion-Version': '2022-02-22'
}

data = {'children': [{'object': 'block',
        'type': 'table',
        'table': {'table_width': 4}}]}

response = requests.patch('https://api.notion.com/v1/blocks/d5e1064a-c6aa-49e2-9f25-4111feac84ca/children', headers=headers, json=data)

This returns following error:

b'{"object":"error","status":400,"code":"validation_error","message":"body failed validation: body.children[0].table.children should be defined, instead was `undefined`."}'

But when I add just a heading everything works fine:

data = {'children': [{'object': 'block',
        'type': 'heading_2',
        'heading_2': {'rich_text': [{'type': 'text',
        'text': {'content': 'blah-blah'}}]}}]}

I literally google everything possible with my error or examples of the api usage


Solution

  • https://developers.notion.com/reference/block#table-rows

    When creating a table block via the Append block children endpoint, the table must have at least one table_row whose cells array has the same length as the table_width.

    fallowing the reference, table attribute should be included children with table_row. and table_row should be included cells array which is same length of table_width.

    here is my test json object.

      "type": "table",
      "table": {
        "table_width": 2,
        "children":[
          {"type": "table_row",
           "table_row": {
             "cells":[
              [
                {
                  "type": "text",
                  "text": {
                    "content": 'test1',
                  }
                }],
              [{
                "type": "text",
                "text": {
                  "content": 'test2',
                }
              }
            ],
            ]
           }
         }
       ]
      }
    }
    

    each row is 'table_row', if you want to add multiple row, add 'table_row' with same length of table_width.