Skip to content

Authentication

This module provides functions to help authenticate with Todoist using the OAuth protocol.

Quick start

import uuid
from todoist_api_python.authentication import get_access_token, get_authentication_url

# 1. Generate a random state
state = uuid.uuid4()

# 2. Get authorization url
url = get_authentication_url(
    client_id="YOUR_CLIENT_ID",
    scopes=["data:read", "task:add"],
    state=uuid.uuid4()
)

# 3.Redirect user to url
# 4. Handle OAuth callback and get code
code = "CODE_YOU_OBTAINED"

# 5. Exchange code for access token
auth_result = get_access_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

For detailed implementation steps and security considerations, refer to the Todoist OAuth documentation.

get_auth_token(client_id, client_secret, code, session=None)

Get access token using provided client ID, client secret, and auth code.

Source code in todoist_api_python/authentication.py
def get_auth_token(
    client_id: str, client_secret: str, code: str, session: Session | None = None
) -> AuthResult:
    """Get access token using provided client ID, client secret, and auth code."""
    endpoint = get_oauth_url(ACCESS_TOKEN_PATH)
    session = session or requests.Session()
    data = {
        "client_id": client_id,
        "client_secret": client_secret,
        "code": code,
    }
    response: dict[str, Any] = post(session=session, url=endpoint, data=data)
    return AuthResult.from_dict(response)

get_authentication_url(client_id, scopes, state)

Get authorization URL to initiate OAuth flow.

Source code in todoist_api_python/authentication.py
def get_authentication_url(client_id: str, scopes: list[Scope], state: str) -> str:
    """Get authorization URL to initiate OAuth flow."""
    if len(scopes) == 0:
        raise ValueError("At least one authorization scope should be requested.")

    endpoint = get_oauth_url(AUTHORIZE_PATH)
    query = {
        "client_id": client_id,
        "scope": ",".join(scopes),
        "state": state,
    }
    return f"{endpoint}?{urlencode(query)}"

revoke_auth_token(client_id, client_secret, token, session=None)

Revoke an access token.

Source code in todoist_api_python/authentication.py
def revoke_auth_token(
    client_id: str, client_secret: str, token: str, session: Session | None = None
) -> bool:
    """Revoke an access token."""
    # `get_api_url` is not a typo. Deleting access tokens is done using the regular API.
    endpoint = get_api_url(ACCESS_TOKENS_PATH)
    session = session or requests.Session()
    params = {
        "client_id": client_id,
        "client_secret": client_secret,
        "access_token": token,
    }
    return delete(session=session, url=endpoint, params=params)