I. Introduction

This development report aims to demonstrate how to use the Notion API to automate workout scheduling. Notion is an all-in-one productivity tool that allows users to create and organize databases, notes, tasks, and much more. The Notion API provides developers with programmatic access to Notion’s features, enabling the automation of various tasks.

The code snippet provided showcases how to use the Notion API to create workout events in a database based on a predefined schedule. The script fetches the existing events within a specific date range and creates new events for the days that do not have any scheduled events. The workout schedule is defined in the days_of_week dictionary, which maps each day of the week to a workout name and a list of tags.

By automating the workout scheduling process with Notion API, developers can save time and reduce manual errors. This report will provide a step-by-step guide to help you set up the Notion API and understand the code snippet’s various components.

II. Setting up the Notion API

To use the Notion API, you need to have a Notion account and an integration set up. Here’s a step-by-step guide to authenticate to the Notion API:

  1. Create an integration in Notion

    • Log in to Notion and navigate to the Integrations page by clicking on your profile icon on the bottom left corner of the screen and then clicking on “Integrations”.
    • Click on the “Create a new integration” button.
    • Give your integration a name and select the workspace where you want to use it.
    • Click on the “Submit” button to create the integration.
  2. Get your integration token

    • Once your integration is created, you can get your integration token by clicking on the integration’s name.
    • Copy the integration token to use it in your code.
  3. Install the Notion API package

    • Open your terminal or command prompt.

    • Run the following command to install the Notion API package:

      pip install notion-client
      
  4. Set up the Notion API client

    • Import the Notion API client in your code by adding the following line at the top:

      from notion_client import Client
      
    • Authenticate the client by adding the following line and replacing <API Key> with your integration token:

      notion = Client(auth="<API Key>")
      
  5. Set up database details

    • Obtain the database ID of the database where you want to add events.
    • Replace the database_id variable in the code snippet with your database ID.

The code snippet provided uses the notion_client.Client object to interact with the Notion API. The Client object is used to authenticate the API client and provides access to various Notion resources, such as databases and pages.

The database_id variable is set to the ID of the Notion database where the workout events will be added. The ID can be found in the database’s URL.

III. Defining the Workout Schedule

The workout schedule is defined in the code snippet using the following variables:

  • start_days_ago: the number of days before today’s date to start the schedule
  • end_days_after: the number of days after today’s date to end the schedule
  • days_of_week: a dictionary that maps each day of the week to a workout name and a list of tags.

The days_of_week dictionary is used to define the workout plan for each day of the week. Each day of the week is a key in the dictionary, and the corresponding value is another dictionary that contains the workout name and a list of tags associated with the workout. For example:

days_of_week = {
    "Monday": {"name": "DAY 1", "tag": ["chest", "triceps"]},
    "Tuesday": {"name": "DAY 2", "tag": ["back", "biceps"]},
    "Wednesday": {"name": "DAY 3", "tag": ["lower body", "shoulder"]},
    "Thursday": {"name": "DAY 1", "tag": ["chest", "triceps"]},
    "Friday": {"name": "DAY 2", "tag": ["back", "biceps"]},
    "Saturday": {"name": "DAY 3", "tag": ["lower body", "shoulder"]},
}

In this example, the schedule is divided into three days, and each day has a specific workout and tags associated with it.

The start_days_ago and end_days_after variables are used to define the date range for the workout schedule. start_days_ago specifies how many days before today’s date to start the schedule, and end_days_after specifies how many days after today’s date to end the schedule.

The code snippet uses the datetime module to obtain today’s date and calculate the start and end dates for the workout schedule. The start date is obtained by subtracting start_days_ago from today’s date, and the end date is obtained by adding end_days_after to today’s date. The dates are formatted as strings in the %Y-%m-%d format.

IV. Querying Existing Events

Before creating new workout events, the code snippet fetches the existing events within the defined date range. This is done to avoid creating duplicate events on the same date.

The notion.databases.query() method is used to query the Notion database and retrieve the existing events. The filter parameter is used to specify the filter conditions for the query. In this case, the filter is set to retrieve events that fall within the start and end dates defined in the code snippet. Here’s an example of the filter used in the query:

{
    "and": [
        {"property": "Date", "date": {"on_or_after": start_date}},
        {"property": "Date", "date": {"on_or_before": end_date}}
    ]
}

This filter returns events that have a Date property that falls between the start_date and end_date.

The results attribute of the query response is used to obtain the existing events within the date range. The results are stored in the existing_events variable for later use in the code snippet.

existing_events = notion.databases.query(
    **{
        "database_id": database_id,
        "filter": {
            "and": [
                {"property": "Date", "date": {"on_or_after": start_date}},
                {"property": "Date", "date": {"on_or_before": end_date}}
            ]
        },
    }
).get("results")

V. Creating New Events

Once the existing events within the date range are obtained, the code snippet proceeds to create new workout events for each day within the schedule date range.

The code snippet uses a for loop to iterate through each date in the date range. A new event is created for each day that is not a Sunday:

for date in (datetime.now() + timedelta(days=n) for n in range(-start_days_ago, end_days_after + 1)):
    # skip Sundays
    if date.strftime("%A") == "Sunday":
        continue

The strftime() method is used to obtain the weekday name from the date, and if the weekday name is “Sunday”, the loop skips that day and moves on to the next day.

The code snippet then checks whether an event already exists on the current date:

if any(event.get("properties").get("Date").get("date").get("start") == date.strftime("%Y-%m-%d") for event in existing_events):
    print(f"Event already exists for {date.strftime('%Y-%m-%d')}. Skipping.")
    continue

If an event already exists on the current date, the loop skips that day and moves on to the next day.

If no event exists on the current date, a new event is created with the workout name and tags associated with that day of the week:

day_of_week = date.strftime("%A")
event_name = days_of_week[day_of_week]["name"]
event_tag = days_of_week[day_of_week]["tag"]
new_event = {
    "Name": {"title": [{"text": {"content": event_name}}]},
    "Date": {"date": {"start": date.strftime("%Y-%m-%d")}},
    "Tag": {"multi_select": [{"name": tag} for tag in event_tag]},
}
notion.pages.create(parent={"database_id": database_id}, properties=new_event)

The workout name and tags associated with that day of the week are obtained from the days_of_week dictionary. The new_event dictionary is used to define the properties of the new event, which includes the event name, date, and tags. The notion.pages.create() method is used to create the new event in the Notion database.

By creating new events for each day of the week within the schedule date range, developers can automate the workout scheduling process and ensure that the workout plan is up-to-date and accurate.

VI. Conclusion

In this project, we have demonstrated how to use the Notion API to automate the process of creating a workout schedule in a Notion database. The code snippet we provided can be used to create a workout schedule for a specific date range and automatically add new events to the database based on the defined workout plan.

The Notion API can be used to automate a wide range of tasks, such as managing a to-do list, tracking expenses, or organizing project tasks. With the Notion API, developers can build custom integrations and automate repetitive tasks, saving time and increasing productivity.

Overall, the Notion API provides a powerful tool for developers to integrate Notion into their workflow and automate their tasks. As Notion continues to grow in popularity, we can expect to see more developers building integrations and automating tasks with the Notion API.

In the future, we plan to expand on this project by adding more features and integrations with other tools. We also plan to explore other use cases for the Notion API and see how it can be used to automate other tasks in our workflow.


Source code : https://github.com/hobbyworker/notion-workout-scheduler