Hugging Face API Token: Create, Secure, and Use
What you’ll build
Section titled “What you’ll build”By the end of this guide you will have a Hugging Face access token stored in an environment variable, the correct permission level set for your use case, and a working Python call that returns a model inference result. You will also know how to request access to gated models such as Llama and Gemma.
Prerequisites
Section titled “Prerequisites”| Requirement | Notes |
|---|---|
| Hugging Face account | Sign up at huggingface.co/join |
| Verified email | Required before creating tokens |
| Python 3.9+ | To run the verification samples |
huggingface_hub and requests |
Installed in the verification step |
No payment method is needed for the free Inference API tier.
Step 1 — Create the token
Section titled “Step 1 — Create the token”- Sign in at huggingface.co.
- Click your profile picture (top-right) and go to Settings › Access Tokens, or visit huggingface.co/settings/tokens directly.
- Click New token.
- Give it a descriptive name (for example
orders-portal-dev). - Select the Role:
- Read — download models and datasets, use the Inference API. Use this by default.
- Write — also allows uploading models, datasets, and creating repositories.
- Admin — full access including deleting repositories. Avoid this for application keys.
- Click Generate a token and copy it immediately. The token starts with
hf_. Unlike some providers, Hugging Face lets you view the token again later from the settings page, but copying it now is good practice.
Step 2 — Store the token securely
Section titled “Step 2 — Store the token securely”Linux / macOS (current shell session):
export HF_TOKEN="hf_your-token-here"Windows PowerShell (current session):
$env:HF_TOKEN = "hf_your-token-here".env file for local development (add .env to .gitignore):
HF_TOKEN=hf_your-token-hereLoad it in Python with python-dotenv:
from dotenv import load_dotenvload_dotenv()Alternatively, use the CLI to log in once and store the token locally:
huggingface-cli loginThis saves the token to ~/.cache/huggingface/token, which the library reads automatically without requiring an environment variable.
Step 3 — Verify the token works
Section titled “Step 3 — Verify the token works”Install the library and make a minimal inference request.
pip install huggingface_hub requestsSave as check_token.py and run with python check_token.py (Python 3.9+):
import osimport requests
token = os.environ["HF_TOKEN"]api_url = "https://api-inference.huggingface.co/models/distilbert/distilbert-base-uncased-finetuned-sst-2-english"headers = {"Authorization": f"Bearer {token}"}
response = requests.post(api_url, headers=headers, json={"inputs": "This setup works perfectly."})print(response.json())# Expected: [{"label": "POSITIVE", "score": 0.99...}]A 401 Unauthorized response means the token is missing or wrong. A 503 Service Unavailable means the model is loading — wait a few seconds and retry.
Accessing gated models
Section titled “Accessing gated models”Some models (Llama, Gemma, Mistral) require you to agree to a license before downloading. The token alone is not enough.
- Go to the model card page on Hugging Face (for example huggingface.co/meta-llama/Llama-3.1-8B).
- Click Request access and fill in the form.
- Wait for approval — this is usually automated and takes a few minutes for Meta models.
- Once approved, download with your token:
from huggingface_hub import snapshot_downloadimport os
snapshot_download( repo_id="meta-llama/Llama-3.1-8B", token=os.environ["HF_TOKEN"], local_dir="./models/llama-3.1-8b",)Permission levels
Section titled “Permission levels”| Role | Download public models | Use Inference API | Upload models | Delete repos |
|---|---|---|---|---|
| Read | Yes | Yes | No | No |
| Write | Yes | Yes | Yes | No |
| Admin | Yes | Yes | Yes | Yes |
Create separate tokens for different environments. Use Read tokens for applications that only run inference; Write tokens belong in deployment pipelines, not application code.
Managing tokens
Section titled “Managing tokens”View tokens: Settings › Access Tokens shows each token’s name, role, creation date, and last-used timestamp.
Revoke a token: Click the trash icon and confirm. Any application using it immediately receives 401 Unauthorized.
Rename a token: Click the pencil icon. This does not change the token value.
Troubleshooting
Section titled “Troubleshooting”| Error | Likely cause | Fix |
|---|---|---|
401 Unauthorized |
Token missing, wrong value, or revoked | Re-check the Authorization: Bearer header. Verify the token in settings. |
403 Forbidden |
Gated model — access not granted | Request access on the model card page. |
503 Service Unavailable |
Model is loading (cold start) | Retry after 20–30 seconds. |
| Rate limit exceeded | Free tier quota hit | Wait for the quota to reset, or upgrade to Inference Endpoints. |
Next steps
Section titled “Next steps”- AI and ML basics — grounding concepts before diving into models
- Python AI packages —
transformers,datasets, and related libraries - API Tokens overview — comparison of all supported providers
Official references
Section titled “Official references”- Hugging Face Hub documentation — tokens, repos, and gated access
- Inference API documentation — serverless inference endpoints
- huggingface_hub Python library — download, upload, and authenticate
- Access tokens settings — manage your tokens