Daily Task Automator (+ Notion API with Python) - Tutorial
Tags: notion, notionapi, python, tutorial
Published: 2023-01-08 10:16:37

**In this tutorial**, I'll show you how to set your own Task Automation System with Notion and Python.

## Brief Introduction:

We have to follow these two main steps:

1. Notion integration setup
2. Python code setup

The link between these two steps, lie in the magic of Notion API.

If you're new to Notion API and Notion Integration itself, I'll explain how you can get started with it in this tutorial.

### Want the Notion Template? Get it here!

If you dont have access to the notion template yet, get it [👉🏻 here](https://tnvmadhav.me/products/daily-task-automator/)👈🏻

Now that you've gotten your hands on this template and duplicated into your workspace, let's get started:

## The Notion integration setup 

This step ensures the python script makes updates to the right notion database.

To ensure this, the python code needs to first 'identify' the notion database so that it can 'talk' to it.

Each notion database has a unique id that is part of the url link.

To make this process easier, we can create a 'secret token' that can be used to connect to your notion database.

Let's do just that,

### 1. Create notion integration secret token

> If you haven't already, create a free [Notion](https://notion.so/) Account

1. Go to https://notion.so/my-integrations/

2. Click `+ New Integration` button
    
![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e78ysl76m3wkm41qthga.png)

3. Give name `My Notion Task Automator` and submit

    
![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kv7fu48ydadn1wia03pd.png))

4. Show and copy secret token (keep it aside safely)
     
![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sgjrwy2e8w5basl1nd15.png)    
5. Click `Save Changes`
    
![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pitjh2g1fgedw2kl1wg.png)

> Copy and keep the notion integration secret token so that you can later share it to your python script.

### 2. Connect it to the notion page

1. Click `...` on the top right corner

    
![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/an0qujeerd41d7kzl9og.png)

2. Click on `Add Connections` and search and select the newly created Notion Integration
    
![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfr37u4migesxhol56c0.png)

### 3. Create tasks to automatically populate everyday

Let’s start with a simple habit,

> 💪 “Doing 10 pushups at 10:30 AM — everyday of the week”

In **Task Definition** notion database, click `+ new`, and create a new task:

1. Task Name `Perform 10 Pushups`
2. Date `10:30 AM` (any date but time should be 10:30 AM)
3. Days of the week `(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)`

 Here is how it will look like,


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/14jcn6kx20o17wdode4h.png) Tasks into the Task Definition database](/2.png)


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c6vulvgnmmne52qo4lgc.png)

Woo-hoo! Look at you!

Now let's focus on running the python script. Jumping right in:

## The Python code setup

To do this, you don't have to run python on your PC or laptop. 

You can:

### 1. Create a free account on [Replit](https://replit.com/) and login,


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xcrx3aidj5yjc0rx1tjo.png)


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rkpg0ibxy3vxpeaewqjo.png)


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5bgos9ntar40hzmxyqk.png)

### 2.  Copy and paste the python code

Copy the below python code:

```python
import requests
import json
from datetime import date
import calendar
import os
import dateutil.parser
import datetime


class MyNotionIntegration:

    def __init__(self):
      self.headers = {
        'Content-Type': 'application/json',
        'Notion-Version': '2021-05-13',
        'Authorization': f'Bearer {os.getenv("NOTION_DAILY_TASK_SCHEDULER_INTEGRATION_SECRET")}'
      }
      self.read_db = self.write_db = self.list_of_tasks = None

    @staticmethod
    def getSameTimeButToday(date_string):
      if not date_string:
        return
      iso_parser = dateutil.parser.isoparse(date_string)
      today_date_obj = iso_parser.replace(
        day=datetime.datetime.now().day,
        month=datetime.datetime.now().month,
        year=datetime.datetime.now().year,
      )
      return today_date_obj.isoformat('T')

    def getReadAndWriteDBs(self, name=None):
      if not name:
        name = "TASKS TEMPLATE"
      url = "https://api.notion.com/v1/search/"
      payload = json.dumps({
        "filter": {
          "property": "object",
          "value": "database"
        }
      })
      response = requests.request("POST", url, headers=self.headers, data=payload)
      databases = response.json().get('results')
      for database in databases:
        if database.get('title')[0].get('text').get('content').upper() == name:
          self.read_db = database
        else:
          self.write_db = database

    def getTodaysTasks(self):
      url = f"https://api.notion.com/v1/databases/{self.read_db.get('id')}/query"
      payload = json.dumps({
        "filter": {
          "property": "Day of the Week",
          "multi_select": {
             "contains": calendar.day_name[date.today().weekday()]
          }
        }
      })
      response = requests.request("POST", url, headers=self.headers, data=payload)
      self.list_of_tasks = response.json().get('results')

    def createTasks(self):
      url = "https://api.notion.com/v1/pages/"
      for task in self.list_of_tasks:
        print(task.get('properties').get('Date').get('date').get('start'))
        payload = json.dumps({
          "parent": {
            "type": "database_id",
            "database_id": self.write_db.get('id'),
          },
          "icon": task.get('icon'),
          "properties": {
            "Due For": {
              "type": "date",
              "date": {
                "start": self.getSameTimeButToday(
                  task.get('properties').get('Date').get('date').get('start')
                ),
                "end": self.getSameTimeButToday(
                  task.get('properties').get('Date').get('date').get('end')
                ),
              }
            },
            "Task": {
              "type": "title",
              "title": [
                {
                  "type": "text",
                  "text": {
                    "content": task.get('properties').get('Name').get('title')[0].get('plain_text'),
                  },
                  "plain_text": task.get('properties').get('Name').get('title')[0].get('plain_text'),
                }
              ]
            }
          }
        })
        response = requests.request("POST", url, headers=self.headers, data=payload)
        print(f"HTTP Status {response.status_code}", response.text)

    def RunWorkflow(self):
      self.getReadAndWriteDBs()
      self.getTodaysTasks()
      self.createTasks()

if __name__ == "__main__":
  MyNotionIntegration().RunWorkflow()
```

![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7q4dc2z3l3evmzj72946.png)![Replit setup](/6.png)

### 3.  Share the notion integration secret key with the python script


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/222ijetl7o7pvqvqfxs9.png)

![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwe4t9i40kb4frtk38pa.png)


### 4.  Run the script from your browser!


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bns4t4gnwjgjui0ri9og.png)


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9nyhbq0inm9zl8u2f6r.png)

> After running the Python script on Replit, you can see that today’s tasks are auto-populated in Task Automator database.


![Daily Task Automator (+ Notion API with Python) - Tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wunh6xkovlk6xmrt2117.png)

> 🥳 Nice! You now have a automated todo-list!

Add any habits to the `Task Definition` database and run the python script on replit (automation) every day to auto generate the todo-list in the `Task Automator` database.

## 😆 Thank you

...for being part of this experiment and hope you use this to enhance your productivity 😃

> If you dont have access to the notion template yet, get it [👉🏻 here](https://tnvmadhav.me/products/daily-task-automator/)👈🏻

If you liked this product, you'll probably love my **other products** which can be found [🔗 👉🏻 here](https://tnvmadhav.me/products/)👈🏻

Let's connect on Twitter [@TnvMadhav](https://twitter.com/TnvMadhav/) if you don't wanna miss out on newer projects!