Notion API 키 발급 https://www.notion.so/profile/integrations
Notion Database에서 1번 api 연결
Notion Database의 id 얻기
id 추출
api 호출
API 호출 메소드는 POST여야 합니다.
호출할 API의 url은 다음과 같습니다.
https://api.notion.com/v1/databases/{{데이터베이스 아이디}}/query
header는 다음과 같이 3개를 입력해야 합니다.
Authorization | Bearer {{api 시크릿 키}} |
---|---|
Notion-Version | 노션 api 버전입니다. 최신버전으로 하시면 됩니다. |
버전은 아래 링크에서 확인할 수 있습니다. | |
https://developers.notion.com/reference/changes-by-version | |
Content-Type | application/json |
api 확인
page에서 가져오면 따로 필요한 것 같은데…. 일단 표 안에서 text 받아서 가져오는 걸로 변경
예시 코드
notion_api.py
import os
import requests
import json
from datetime import datetime
from dotenv import load_dotenv
import logging
# dotenv를 통해 환경 변수 로드
load_dotenv()
# 환경 변수에서 민감한 정보 가져오기
DATABASE_URL = os.getenv("NOTION_DATABASE_URL")
NOTION_TOKEN = os.getenv("NOTION_API_TOKEN")
NOTION_VERSION = os.getenv("NOTION_VERSION") # 기본값 설정
# 헤더에 환경 변수 적용
headers = {
"Authorization": f"Bearer {NOTION_TOKEN}",
"Content-Type": "application/json",
"Notion-Version": NOTION_VERSION
}
# 로깅 설정
logging.basicConfig(
filename='notion_api.log', # 로그 파일 이름
level=logging.ERROR, # 로그 수준
format='%(asctime)s - %(levelname)s - %(message)s', # 로그 포맷
)
# Notion API URL
def fetch_data_from_notion():
"""Notion API에서 데이터 가져오기"""
logging.info("Fetching data from Notion API.")
response = requests.post(DATABASE_URL, headers=headers)
if response.status_code == 200:
logging.info("Data fetched successfully.")
return response.json()
else:
logging.error(f"Request failed: {response.status_code}")
logging.error(response.text)
return None
def extract_dates():
"""오늘 날짜를 반환"""
today_date = datetime.today().strftime('%Y-%m-%d')
logging.info(f"Today's date: {today_date}")
return today_date
def process_page_data(data, today_date):
"""페이지 데이터를 순회하면서 어제 날짜에 해당하는 데이터를 찾고 처리"""
logging.info("Processing page data.")
for page in data.get('results', []):
created_date = page['created_time'].split('T')[0]
if created_date == today_date:
contents = page['properties'].get('contents', {}).get('rich_text', [{}])[0].get('text', {}).get('content', '')
learn = page['properties'].get('learn', {}).get('rich_text', [{}])[0].get('text', {}).get('content', '')
logging.info(f"Found data for today: {created_date}")
return created_date, contents, learn
logging.info("No data found for today.")
return None, None, None
def save_data_to_file(created_date, contents, learn, today_date):
"""파일로 데이터를 저장"""
logging.info(f"Saving data to file: {today_date.replace('-', '')}.json")
final_result = {created_date: {'contents': contents, 'learn': learn}}
file_name = f"{today_date.replace('-', '')}.json" # yymmdd 형태로 파일명 생성
with open(file_name, 'w') as json_file:
json.dump(final_result[created_date], json_file, indent=4, ensure_ascii=False)
logging.info(f"File '{file_name}' has been created/overwritten.")
def main():
# 데이터 가져오기
logging.info("Starting the process.")
data = fetch_data_from_notion()
if not data:
logging.error("No data fetched. Exiting the process.")
return
# 오늘과 어제 날짜 추출
today_date = extract_dates()
# 페이지 데이터 처리
created_date, contents, learn = process_page_data(data, today_date)
# 처리된 데이터가 있으면 파일로 저장
if created_date:
save_data_to_file(created_date, contents, learn, today_date)
else:
logging.warning("No data for today's date.")
if __name__ == "__main__":
main()
shell script
#!/bin/bash
# 스크립트 실행 중 에러 발생 시 중단
set -e
# git branch 이름
BRANCH_NAME="master"
# 실행할 Python 파일 경로
PYTHON_FILE="notion_api.py"
# Git 저장소 업데이트
echo "Pulling the latest changes from the repository..."
git pull origin $BRANCH_NAME
# Python 파일 실행
if [ -f "$PYTHON_FILE" ]; then
echo "Running Python script: $PYTHON_FILE"
python3 "$PYTHON_FILE"
else
echo "Error: $PYTHON_FILE not found!"
exit 1
fi
# Git 상태 확인
echo "Checking for new files..."
git add .
# 변경사항이 있는지 확인
if git diff --cached --quiet; then
echo "No new files to commit."
else
# 커밋 및 푸시
echo "New files detected. Committing and pushing changes..."
git commit -m "Automated commit: Added new files after Python script execution"
git push origin $BRANCH_NAME
echo "Changes have been pushed successfully."
fi
git repo를 연결해서 pr 또는 issue를 notion table에 동기화 시킬 수도 있다.