Skip to content

Auto-authentication consumes KAGGLE_API_TOKEN before user code runs #882

@djhuangit

Description

@djhuangit

Description

The kaggle/__init__.py auto-authenticates on import and removes KAGGLE_API_TOKEN from the environment. This breaks programmatic usage - users cannot create their own KaggleApi() instance because the token is already consumed.

Environment

  • kaggle: 1.8.2
  • Python: 3.13.5
  • OS: macOS

Steps to Reproduce

Using the officially documented pattern from the README:

import os
os.environ["KAGGLE_API_TOKEN"] = "KGAT_xxxxx"

# Official pattern from README:
import kaggle
from kaggle.api.kaggle_api_extended import KaggleApi

api = KaggleApi()
api.authenticate()
# Fails - token was already consumed by `import kaggle`

Root Cause

Two things combine to cause this:

  1. kaggle/__init__.py auto-authenticates on import:
api = KaggleApi(enable_oauth=enable_oauth)
api.authenticate()
  1. _authenticate_with_access_token() removes the token after use:
os.environ.pop("KAGGLE_API_TOKEN", None)

Workaround

Use the pre-authenticated API instance from kaggle module instead of creating a new one:

# Instead of:
from kaggle.api.kaggle_api_extended import KaggleApi
api = KaggleApi()
api.authenticate()

# Use:
import kaggle
api = kaggle.api  # Already authenticated on import

# Then use normally:
files = api.dataset_list_files("uciml/iris")
api.dataset_download_files("uciml/iris", path="./data")

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions