Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macoril/b6bba1aa7cd707b66d8aa297ccf85207 to your computer and use it in GitHub Desktop.
Save macoril/b6bba1aa7cd707b66d8aa297ccf85207 to your computer and use it in GitHub Desktop.
This code is to retrieve records from a Notion table filtering by the value of a date property and notify on a Slack channel via Zapier.
"""
# This code works on a Zapier Action of "Code by Zapier" choosed its "Action Event" as "Run Python".
# Please set some values as "Input Data"
# - NOTION_BEARER_TOKEN : e.g. Bearer secret_aBcDefg...
# - NOTION_VERSION : e.g. 2022-02-22
# - DATABASE_ID : e.g. 12ab3c...
# - PROPERTY_NAME_OF_LAST_CONTACT_DATE : e.g. last contacted at
# - PROPERTY_NAME_OF_CHURN_DATE : e.g. churned at
"""
import json
from datetime import datetime, date, timedelta
from dateutil.relativedelta import relativedelta
# e.g. equals, after, before, etc...
# ref: https://developers.notion.com/reference/post-database-query-filter#date-filter-condition
filter_condition = 'on_or_before'
# Calculate the date for filtering
today = datetime.today()
one_month_ago = today - relativedelta(months = 1)
target_date = datetime.strftime(one_month_ago, '%Y-%m-%d')
# Generate headers and a payload for a request.
base_url = 'https://api.notion.com/v1'
url = base_url + '/databases/{id}/query'.format(id = input_data['DATABASE_ID'])
headers = {
'Content-Type' : 'application/json'
,'Authorization' : input_data['NOTION_BEARER_TOKEN']
,'Notion-Version' : input_data['NOTION_VERSION']
}
payload = json.dumps({
"filter": {
"property" : input_data['TARGET_PROPERTY_NAME']
,"date" : {
filter_condition : target_date
}
}
})
# Send a request and get a response of it
response = requests.post(url, headers = headers, data = payload)
response.raise_for_status()
# Set an output that aligns contents of the response for subsequent actions.
output = {
'response' : response.json()
,'amount of customers' : len(response.json().get('results'))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment