Kaggle API Client

0.1.18 · active · verified Sat Apr 11

The `kagglesdk` is the official Python client library for interacting with Kaggle's external-facing APIs, allowing users to programmatically access competitions, datasets, kernels, and more. It is currently at version 0.1.18 and receives frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with the Kaggle API client and then use it to list active competitions. It also includes a commented-out example for downloading a dataset. Ensure your Kaggle API credentials (`kaggle.json` file or `KAGGLE_USERNAME`, `KAGGLE_KEY` environment variables) are correctly configured before running.

import os
import kaggle

# --- Kaggle API Authentication ---
# The client expects credentials in one of two ways:
# 1. A `kaggle.json` file in `~/.kaggle/` (recommended for local development)
# 2. Environment variables: `KAGGLE_USERNAME` and `KAGGLE_KEY`
# For example, in your shell:
# export KAGGLE_USERNAME="your_username"
# export KAGGLE_KEY="your_api_key"

# Initialize and authenticate the API client
# This call implicitly uses the `kaggle.json` file or environment variables.
kaggle.api.authenticate()

print("Successfully authenticated to Kaggle API.")

# --- Example Usage: List active competitions ---
print("\nActive Competitions:")
try:
    # competition_list returns a generator-like object
    competitions = kaggle.api.competition_list(category='active', sort_by='recentlyStarted')
    for competition in competitions:
        print(f"- {competition.ref}: {competition.title}")
except Exception as e:
    print(f"Error listing competitions: {e}")

# --- Example Usage: Download a dataset (uncomment to run) ---
# dataset_name = 'titanic'
# download_path = './data'
# os.makedirs(download_path, exist_ok=True)
# print(f"\nDownloading dataset '{dataset_name}' to '{download_path}'...")
# try:
#     kaggle.api.dataset_download_files(dataset_name, path=download_path, unzip=True)
#     print(f"Dataset '{dataset_name}' downloaded and unzipped successfully.")
# except Exception as e:
#     print(f"Error downloading dataset '{dataset_name}': {e}")

view raw JSON →