How to Create a Hugging Face API Token | Complete Guide
🔑 How to Create a Hugging Face API Token
Section titled “🔑 How to Create a Hugging Face API Token”Learn how to create and manage Hugging Face API tokens to access thousands of open-source AI models, datasets, and spaces on the Hugging Face Hub.
🔹 What is a Hugging Face API Token?
Section titled “🔹 What is a Hugging Face API Token?”A Hugging Face API token (also called Access Token) allows you to:
- Access and download models from Hugging Face Hub
- Use the Inference API for model predictions
- Upload and manage your own models and datasets
- Authenticate with Hugging Face services
- Access private or gated models and datasets
🔹 Prerequisites
Section titled “🔹 Prerequisites”Before creating an API token, you need:
- Hugging Face Account → Sign up at https://huggingface.co/join
- Email Verification → Verify your email address
- Internet Connection → For API access
🔹 Step-by-Step: Creating a Hugging Face API Token
Section titled “🔹 Step-by-Step: Creating a Hugging Face API Token”Step 1: Sign in to Hugging Face
Section titled “Step 1: Sign in to Hugging Face”- Go to Hugging Face
- Click “Sign in” in the top-right corner
- Log in with your credentials
Step 2: Navigate to Access Tokens
Section titled “Step 2: Navigate to Access Tokens”- Click on your profile picture (top-right corner)
- Select “Settings” from the dropdown menu
- Click on “Access Tokens” in the left sidebar
Or go directly to: https://huggingface.co/settings/tokens
Step 3: Create a New Token
Section titled “Step 3: Create a New Token”-
Click “New token” button
-
Fill in the token details:
- Name: Give it a descriptive name (e.g., “My Python App”, “Production API”)
- Role: Choose the permission level:
- Read → Only read access (recommended for most uses)
- Write → Allows uploading models and datasets
- Admin → Full access (use with caution)
-
Click “Generate a token”
Step 4: Copy Your Token
Section titled “Step 4: Copy Your Token”⚠️ IMPORTANT: Save your token immediately!
- Copy the token that appears
- Store it securely in a password manager or environment variable
- You can view it again later, but it’s best to save it now
Example token format:
hf_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890🔹 Token Permission Levels
Section titled “🔹 Token Permission Levels”Read Token:
Section titled “Read Token:”- ✅ Download public models and datasets
- ✅ Access Inference API
- ✅ Use private models you have access to
- ❌ Cannot upload or modify resources
Write Token:
Section titled “Write Token:”- ✅ All Read permissions
- ✅ Upload models and datasets
- ✅ Create and manage repositories
- ✅ Push changes to your repos
Admin Token:
Section titled “Admin Token:”- ✅ All Write permissions
- ✅ Delete repositories
- ✅ Manage organization settings
- ⚠️ Use with extreme caution
🔹 Managing Your Tokens
Section titled “🔹 Managing Your Tokens”View Existing Tokens:
Section titled “View Existing Tokens:”- Go to Access Tokens
- You’ll see all your tokens with:
- Name
- Role (Read/Write/Admin)
- Created date
- Last used timestamp
- Actions (Rename, Revoke)
Rename a Token:
Section titled “Rename a Token:”- Click the pencil icon next to the token
- Enter a new name
- Click “Save”
Revoke/Delete a Token:
Section titled “Revoke/Delete a Token:”- Click the trash icon next to the token
- Confirm the deletion
⚠️ Warning: Revoking a token immediately stops all applications using it.
🔹 API Token Security Best Practices
Section titled “🔹 API Token Security Best Practices”- Use Read tokens by default (only use Write when necessary)
- Store tokens in environment variables or secrets managers
- Use different tokens for different projects
- Revoke tokens you no longer need
- Use
.envfiles for local development - Rotate tokens periodically
❌ DON’T:
Section titled “❌ DON’T:”- Hardcode tokens in source code
- Commit tokens to Git repositories
- Share tokens publicly
- Use Admin tokens unless absolutely necessary
- Reuse the same token across all projects
🔹 Using Your Hugging Face Token
Section titled “🔹 Using Your Hugging Face Token”Method 1: Environment Variable (Recommended)
Section titled “Method 1: Environment Variable (Recommended)”Linux/macOS:
export HF_TOKEN="hf_your-token-here"# orexport HUGGING_FACE_HUB_TOKEN="hf_your-token-here"Windows CMD:
set HF_TOKEN="hf_your-token-here"Windows PowerShell:
$env:HF_TOKEN="hf_your-token-here"Method 2: .env File
Section titled “Method 2: .env File”Create a .env file:
HF_TOKEN=hf_your-token-hereLoad it in Python:
from dotenv import load_dotenvimport os
load_dotenv()token = os.getenv("HF_TOKEN")Method 3: Hugging Face CLI Login
Section titled “Method 3: Hugging Face CLI Login”huggingface-cli loginThis will prompt you to enter your token and save it locally.
🔹 Testing Your Token
Section titled “🔹 Testing Your Token”Python Example - Using Transformers:
Section titled “Python Example - Using Transformers:”from transformers import pipelineimport os
# Set your tokentoken = os.getenv("HF_TOKEN")
# Use a model with authenticationclassifier = pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english", use_auth_token=token)
result = classifier("I love Hugging Face!")print(result)Python Example - Using Inference API:
Section titled “Python Example - Using Inference API:”import requestsimport os
API_URL = "https://api-inference.huggingface.co/models/gpt2"headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}
def query(payload): response = requests.post(API_URL, headers=headers, json=payload) return response.json()
output = query({"inputs": "The answer to the universe is"})print(output)Python Example - Downloading Models:
Section titled “Python Example - Downloading Models:”from huggingface_hub import hf_hub_downloadimport os
token = os.getenv("HF_TOKEN")
# Download a specific file from a modelfile_path = hf_hub_download( repo_id="bert-base-uncased", filename="config.json", use_auth_token=token)
print(f"Downloaded to: {file_path}")cURL Example:
Section titled “cURL Example:”curl https://api-inference.huggingface.co/models/gpt2 \ -H "Authorization: Bearer $HF_TOKEN" \ -H "Content-Type: application/json" \ -d '{"inputs": "Hello, Hugging Face!"}'🔹 Using Tokens with Hugging Face Libraries
Section titled “🔹 Using Tokens with Hugging Face Libraries”Install Required Libraries:
Section titled “Install Required Libraries:”# Core librarypip install huggingface_hub
# For model inferencepip install transformers torch
# For datasetspip install datasetsAuthenticate in Code:
Section titled “Authenticate in Code:”Option 1: Pass token directly
from huggingface_hub import HfApi
api = HfApi(token="hf_your-token-here")Option 2: Use environment variable
from huggingface_hub import HfApiimport os
api = HfApi(token=os.getenv("HF_TOKEN"))Option 3: Use CLI login (token stored automatically)
from huggingface_hub import HfApi
api = HfApi() # Automatically uses saved token🔹 Accessing Private and Gated Models
Section titled “🔹 Accessing Private and Gated Models”Private Models:
Section titled “Private Models:”If you have access to a private model:
from transformers import AutoModelimport os
model = AutoModel.from_pretrained( "username/private-model", use_auth_token=os.getenv("HF_TOKEN"))Gated Models:
Section titled “Gated Models:”Some models require explicit access approval:
- Visit the model page (e.g., LLaMA models)
- Click “Request access”
- Fill out the form and wait for approval
- Once approved, use your token to access:
from transformers import AutoTokenizerimport os
tokenizer = AutoTokenizer.from_pretrained( "meta-llama/Llama-2-7b-hf", use_auth_token=os.getenv("HF_TOKEN"))🔹 Using the Inference API
Section titled “🔹 Using the Inference API”Hugging Face provides a free Inference API with rate limits:
Free Tier Limits:
Section titled “Free Tier Limits:”- Requests per day: Limited (varies by model)
- Rate limiting: May experience delays under heavy load
Pro Tier (Hugging Face Pro):
Section titled “Pro Tier (Hugging Face Pro):”- Higher rate limits
- Priority access
- Faster inference
Check pricing: https://huggingface.co/pricing
🔹 Common Issues and Troubleshooting
Section titled “🔹 Common Issues and Troubleshooting”Issue 1: “Invalid token” Error
Section titled “Issue 1: “Invalid token” Error”Solution:
- Verify the token is copied correctly
- Ensure the token hasn’t been revoked
- Check for extra spaces or newlines
Issue 2: “Access Denied” (401/403 Error)
Section titled “Issue 2: “Access Denied” (401/403 Error)”Solution:
- Token may not have required permissions
- Model may be private or gated
- Request access to gated models if needed
Issue 3: Rate Limit Exceeded
Section titled “Issue 3: Rate Limit Exceeded”Solution:
- You’ve hit the free tier limit
- Wait for the limit to reset
- Consider upgrading to Hugging Face Pro
Issue 4: Token Not Found
Section titled “Issue 4: Token Not Found”Solution:
- Ensure environment variable is set correctly
- Run
huggingface-cli loginto save token locally - Check
.envfile is being loaded
🔹 Uploading Models and Datasets
Section titled “🔹 Uploading Models and Datasets”With a Write token, you can upload your own content:
Upload a Model:
Section titled “Upload a Model:”from huggingface_hub import HfApiimport os
api = HfApi(token=os.getenv("HF_TOKEN"))
api.upload_file( path_or_fileobj="path/to/model.bin", path_in_repo="model.bin", repo_id="username/my-model", repo_type="model")Create a Repository:
Section titled “Create a Repository:”from huggingface_hub import create_repoimport os
create_repo( repo_id="username/my-new-model", token=os.getenv("HF_TOKEN"), private=False)🔹 Organization Tokens
Section titled “🔹 Organization Tokens”If you’re part of an organization:
- Go to Organization Settings
- Select your organization
- Navigate to “Access Tokens”
- Create organization-level tokens
🔹 CLI Commands
Section titled “🔹 CLI Commands”Login:
Section titled “Login:”huggingface-cli loginWhoami (check current user):
Section titled “Whoami (check current user):”huggingface-cli whoamiLogout:
Section titled “Logout:”huggingface-cli logoutUpload a model:
Section titled “Upload a model:”huggingface-cli upload username/model-name ./model_folder🔹 Additional Resources
Section titled “🔹 Additional Resources”- Official Documentation: https://huggingface.co/docs
- Hub Documentation: https://huggingface.co/docs/hub
- Transformers Library: https://huggingface.co/docs/transformers
- Inference API Docs: https://huggingface.co/docs/api-inference
- Community Forum: https://discuss.huggingface.co
- Model Hub: https://huggingface.co/models
- Datasets Hub: https://huggingface.co/datasets
🚀 Conclusion
Section titled “🚀 Conclusion”You now know how to:
✅ Create and manage Hugging Face API tokens
✅ Use different permission levels appropriately
✅ Authenticate with Hugging Face services
✅ Access models, datasets, and APIs
✅ Upload your own content
✅ Troubleshoot common issues
Start building with the world’s largest AI community! 🤗