The todoist_api_python.authentication module provides helpers to implement the OAuth flow. To authenticate a user, you must generate an authorization URL, redirect the user to it, capture the authorization code from the callback, and exchange that code for an access token.
OAuth Flow Steps:
- Generate a random state: Create a unique string (e.g., using
uuid.uuid4()) to prevent CSRF attacks. - Build the authorization URL: Use
get_authentication_url() with your client_id, desired scopes, and the generated state. - Redirect the user: Send the user to the generated URL.
- Handle the callback: After the user authorizes, capture the
code provided in the redirect. - Exchange code for token: Use
get_auth_token() with your client_id, client_secret, and the captured code. - Verify state: Ensure the
state returned in the auth_result matches the state you originally generated.
import uuid
from todoist_api_python.authentication import get_auth_token, get_authentication_url
# 1. Generate a random state
state = str(uuid.uuid4())
# 2. Build the authorization URL
url = get_authentication_url(
client_id="YOUR_CLIENT_ID",
scopes=["data:read", "task:add"],
state=state,
)
# 3. Redirect the user to `url` (handled by your application logic)
# 4. Handle the OAuth callback and obtain the auth code
code = "CODE_YOU_OBTAINED"
# 5. Exchange code for an access token
auth_result = get_auth_token(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET",
code=code,
)
# 6. Ensure state is consistent, and done!
assert auth_result.state == state
access_token = auth_result.access_token