How to Upload Data to a Notion Database

Your compass to discover Notion API with cURL and Python.

saja
Python in Plain English

--

Time to get some Notions (credits)

Notion is a platform designed to blend your workflow into an all-in-one workspace. It has many options and features adapted to all kinds of usage.

I started using Notion recently, and I figured I’d use the Database mode that Notion offers. I wanted to keep track of members subscribed to blef.fr’s newsletter, by uploading every member to a Notion Database.

We’ll walk through the process of creating a database in Notion, and uploading data to it.

First, create a database in your workspace. Go to workspace and add a page. Type ‘/table’ and choose full page table. You’ll then have to create an integration and share your database with this integration, tutorial here.

Now that you got your database ID and your Notion key, you can start making API requests.

We’ll go over Notion requests using cURL and Python.

Requesting Notion’s API using cURL

Here’s what a Notion HTTP request looks like :

curl -X POST https://api.notion.com/v1/pages -H "Authorization: Bearer $NOTION_KEY" -H "Content-Type: application/json" -H "Notion-Version: 2021-08-16" --data @your_json_file.json

Let’s say that your database has four columns, Name, Country, Email and Subscription.

Name is a Title property, Country is a Text field, Email is an email format and Subscription is a Select Option.

To insert data into this database, you must create a JSON file respecting the following format :

JSON format for uploading data to Notion

You can find this JSON file here.

For more information about Notion’s properties objects: documentation.

For more examples on how to use Notion’s API: postman.

Requesting Notion’s API using Python

Start by importing modules json and requests. Store your API headers and API endpoint in variables :

API_ENDPOINT = "https://api.notion.com/v1/pages"
HEADERS = {"Authorization": "Bearer YOUR_API_TOKEN", "Content-Type": "application/json" ,"Notion-Version": "2021-08-16"}

Then open your JSON file containing what you want to add to the database.

with open ('PATH_TO_YOUR_JSON', 'r') as f:
DATA = json.load(f)

Make a POST request with Headers and Data.

r = requests.post(API_ENDPOINT, data=json.dumps(DATA), headers=HEADERS)

Print the request’s content to see the returned message.

print(r.content)

Use the NotionHook I created

I found an unofficial Python API for notion (link here) but I didn’t find anything Airflow related, so I figured I’d make my own Notion Hook (link here). It has three methods: creating a database, retrieving a database and uploading data to a database.

You can also find my Airflow Pull Request here, leave a thumbs up if you come by!

Thank you for reading!

Originally published by saja at blef.fr.

More content at plainenglish.io

--

--