How to beginner · 3 min read

How to set Hugging Face token in python

Quick answer
Set your Hugging Face token in Python by exporting it as an environment variable named HUGGINGFACE_HUB_TOKEN or by passing it directly to the huggingface_hub client. Use os.environ["HUGGINGFACE_HUB_TOKEN"] to access the token securely in your code.

PREREQUISITES

  • Python 3.8+
  • pip install huggingface_hub>=0.15.0
  • Hugging Face account with an API token

Setup environment variable

Export your Hugging Face token as an environment variable to keep it secure and avoid hardcoding it in your code. This method works across all Python scripts and libraries that use the token.

bash
export HUGGINGFACE_HUB_TOKEN="your_hf_token_here"

Step by step usage in Python

Use the huggingface_hub Python library to authenticate with your token. The library automatically reads the HUGGINGFACE_HUB_TOKEN environment variable. Alternatively, you can pass the token explicitly when creating a client.

python
import os
from huggingface_hub import HfApi

# Access token from environment variable
hf_token = os.environ["HUGGINGFACE_HUB_TOKEN"]

# Initialize client with token
api = HfApi(token=hf_token)

# Example: list your models
models = api.list_models()
print(f"Found {len(models)} models on Hugging Face Hub.")
output
Found 1234 models on Hugging Face Hub.

Common variations

  • Use huggingface-cli login to authenticate once and store the token locally.
  • Pass the token directly to functions like from_pretrained() in transformers by setting use_auth_token=hf_token.
  • For scripts, set the environment variable inline: HUGGINGFACE_HUB_TOKEN=your_token python script.py.

Troubleshooting

If you get authentication errors, verify your token is correctly set in HUGGINGFACE_HUB_TOKEN and has the necessary scopes. Use print(os.environ.get("HUGGINGFACE_HUB_TOKEN")) to debug. Also, ensure your huggingface_hub library is up to date.

Key Takeaways

  • Always store your Hugging Face token in the environment variable HUGGINGFACE_HUB_TOKEN for security.
  • Use the huggingface_hub Python library to authenticate and interact with the Hugging Face Hub.
  • Pass the token explicitly when needed, especially in transformers methods using use_auth_token.
  • Use huggingface-cli login for a one-time setup that stores your token locally.
  • Check your token and library version if you encounter authentication issues.
Verified 2026-04
Verify ↗