hf-hub

Library Featured

Rust client for the Hugging Face Hub API

Checked · Sources

Downloads
3,442,405
Dependents
578
Stars
343
Forks
143
Contributors
28
Commits
174
Latest release
1.0.0 ·

About

From the project README ·

Rust client for the Hugging Face Hub API.

hf-hub provides a typed, ergonomic interface for interacting with the Hugging Face Hub from Rust. It is the Rust equivalent of the Python huggingface_hub library.

Both an async interface (HFClient, on by default) and a synchronous interface (HFClientSync, enabled via the blocking feature) are provided. The two mirror each other method-for-method.

Read the full README

Features

  • Repository operations — query model, dataset, and space metadata; create, delete, update, and move repositories
  • File operations — upload files and folders, download files, list repository trees, check file existence
  • Commit operations — create commits with multiple file operations, list commit history, view diffs between revisions
  • Branch and tag management — create and delete branches and tags, list refs
  • User and organization info — whoami, user profiles, organization details, followers
  • Streaming pagination — async list endpoints return impl Stream<Item = Result<T>> for lazy, memory-efficient iteration; blocking counterparts collect into Vec<T>
  • Bucket operations — create, delete, list, and move buckets; upload, download, and delete files within buckets
  • Xet high-performance transfers — support for Hugging Face's Xet storage backend
  • Async or blocking — use HFClient with your own tokio runtime, or HFClientSync for synchronous callers (requires the blocking feature)

Installation

Add to your Cargo.toml:

[dependencies]
hf-hub = "1.0.0"

To use the synchronous interface, enable the blocking feature:

[dependencies]
hf-hub = { version = "1.0.0", features = ["blocking"] }

CLI Installation

The hfrs command-line tool provides a terminal interface to the Hub. Install it with:

cargo install --git https://github.com/huggingface/hf-hub.git hfrs

This builds in release mode by default. Once installed, run hfrs --help to see available commands.

Quick Start

Async
use hf_hub::HFClient;

#[tokio::main]
async fn main() -> hf_hub::HFResult<()> {
    let client = HFClient::new()?;

    // Get model info
    let Ok(info) = client.model("openai-community", "gpt2").info().send().await else {
        unreachable!("handle type guarantees the Model variant");
    };

    println!("Model: {} (downloads: {:?})", info.id, info.downloads);

    Ok(())
}
Blocking

Requires the blocking feature. HFClientSync manages a dedicated tokio runtime internally, so callers do not need their own.

use hf_hub::HFClientSync;

fn main() -> hf_hub::HFResult<()> {
    let client = HFClientSync::new()?;

    let Ok(info) = client.model("openai-community", "gpt2").info().send() else {
        unreachable!("handle type guarantees the Model variant");
    };
    println!("Model: {} (downloads: {:?})", info.id, info.downloads);

    Ok(())
}

The blocking handles (HFClientSync, HFRepositorySync, HFSpaceSync, HFBucketSync) mirror their async counterparts method-for-method. See the blocking_* examples in examples/ for runnable programs.

Usage Examples

List models by author
use futures::StreamExt;
use hf_hub::HFClient;

#[tokio::main]
async fn main() -> hf_hub::HFResult<()> {
    let client = HFClient::new()?;

    let stream = client
        .list_models()
        .author("meta-llama")
        .limit(5_usize)
        .send()?;
    futures::pin_mut!(stream);

    while let Some(model) = stream.next().await {
        let model = model?;
        println!("{}", model.id);
    }

    Ok(())
}
Work with a repository handle
use hf_hub::HFClient;

#[tokio::main]
async fn main() -> hf_hub::HFResult<()> {
    let client = HFClient::new()?;
    let repo = client.model("openai-community", "gpt2");

    let Ok(model_info) = repo.info().send().await else {
        println!("error, not a model");
        return Ok(());
    };
    println!("Model: {}", model_info.id);

    let exists = repo.file_exists().filename("config.json").send().await?;

    println!("config.json exists: {exists}");
    Ok(())
}
Download a file
use std::path::PathBuf;
use hf_hub::HFClient;

#[tokio::main]
async fn main() -> hf_hub::HFResult<()> {
    let client = HFClient::new()?;
    let repo = client.model("openai-community", "gpt2");

    let path = repo
        .download_file()
        .filename("config.json")
        .local_dir(PathBuf::from("/tmp/hf-downloads"))
        .send()
        .await?;

    println!("Downloaded to: {}", path.display());
    Ok(())
}
Upload a file
use hf_hub::HFClient;
use hf_hub::repository::AddSource;

#[tokio::main]
async fn main() -> hf_hub::HFResult<()> {
    let client = HFClient::new()?;
    let repo = client.model("your-username", "your-repo");

    let commit = repo
        .upload_file()
        .source(AddSource::Bytes(b"Hello, world!".to_vec().into()))
        .path_in_repo("greeting.txt")
        .commit_message("Add greeting file")
        .send()
        .await?;

    println!("Committed: {:?}", commit.commit_oid);
    Ok(())
}
Create a repository
use hf_hub::{HFClient, RepoTypeDataset};

#[tokio::main]
async fn main() -> hf_hub::HFResult<()> {
    let client = HFClient::new()?;

    let url = client
        .create_repository()
        .repo_type(RepoTypeDataset)
        .repo_id("your-username/new-model")
        .private(true)
        .exist_ok(true)
        .send()
        .await?;

    println!("Repository URL: {}", url.url);
    Ok(())
}

Authentication and configuration

hf-hub does not read environment variables. HFClient::new() uses the public Hub endpoint without authentication and caches files in .cache/huggingface/hub relative to the current working directory. Configure a token, endpoint, or cache location explicitly with HFClient::builder():

use hf_hub::HFClient;

let client = HFClient::builder()
    .token("hf_xxx")
    .endpoint("https://huggingface.co")
    .cache_dir("/tmp/hf-cache")
    .build()?;
# Ok::<(), hf_hub::HFError>(())

The hfrs CLI continues to support its existing environment-based configuration.

Error Handling

All fallible operations return Result<T, HFError>. The HFError enum provides structured variants for common failure modes:

  • HFError::AuthRequired — 401 response, token is missing or invalid
  • HFError::RepoNotFound — repository does not exist or is inaccessible
  • HFError::BucketNotFound — bucket does not exist or is inaccessible
  • HFError::EntryNotFound — file or path does not exist in the repository or bucket
  • HFError::RevisionNotFound — branch, tag, or commit does not exist
  • HFError::Forbidden — 403 response, insufficient permissions
  • HFError::Conflict — 409 response, resource already exists or conflicts
  • HFError::RateLimited — 429 response, too many requests
  • HFError::Http — other HTTP errors with status code, URL, and response body

WebAssembly support

hf-hub compiles for wasm32-unknown-unknown. On wasm the API surface is the same call shape as native — client.model(owner, name).download_file_stream()…send().await — but only the streaming download path is wired up; methods that touch the filesystem (download_file, snapshot_download, upload_file, the cache and buckets modules, the blocking wrappers) are gated behind #[cfg(not(target_family = "wasm"))]. Pure-HTTP modules (repository, spaces, users) and HTTP-only methods on HFRepository (exists, info, list_*, etc.) are exposed on both targets.

Verify locally with ./scripts/verify_wasm.sh. CI runs the same check in the wasm job of .github/workflows/rust.yml. The wasm/smoke/ crate is a tiny wasm-bindgen library that exercises the wasm-safe surface end-to-end (see wasm/smoke/src/lib.rs).

When modifying client, error, retry, xet, or repository/download.rs, keep the wasm build green — reqwest's wasm backend has a reduced API (no is_connect, no redirect() policy) and its streams are !Send, and filesystem APIs must stay behind #[cfg(not(target_family = "wasm"))] gates.

License

Apache-2.0

Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
Apache-2.0

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

hf-hub beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
hf-hub This page Featured

Rust client for the Hugging Face Hub API

3,442,405 downloads over 30 days 578 343 1.0.0 GPU support unknown No native code found Apache-2.0
hdf5-rust Featured

Thread-safe Rust bindings for the HDF5 library.

253,180 downloads over 30 days 70 85 0.15.1 GPU support unknown Binds native code: hdf5-metno-sys, blosc-src (feature blosc), lzf-sys (feature lzf), mpi-sys (feature mpio), zfp-sys (feature zfp) Apache-2.0 OR MIT
zarrs Featured

A library for the Zarr storage format for multidimensional arrays and metadata

75,052 downloads over 30 days 51 285 0.23.14 GPU support unknown Binds native code: blosc-src (feature blosc), gdeflate-sys (feature gdeflate), zfp-sys (feature zfp), zstd-sys (feature zstd) Apache-2.0 OR MIT
xet-core Listed

Async runtime, configuration, logging, and utility infrastructure for the Hugging Face Xet client tools.

Python bindings

467,103 downloads over 30 days 9 625 1.8.0 GPU support unknown No native code found Apache-2.0
oxen App Listed

Oxen server is a fast data version control backend, supporting local disk and S3. Self host your repositories on your own storage, or use the hosted platform on Oxen.ai. Stores, syncs, and serves versioned datasets, model checkpoints, game assets, studio media, and any large data.

126 binary downloads per release Not applicable 1,208 0.67.0 GPU support unknown Binds native code: librocksdb-sys, lmdb-master-sys, ffmpeg-sys-next (feature ffmpeg), libduckdb-sys (feature docs) Apache-2.0
nebula App Listed Dormant

A Package Manager for Machine Learning Datasets and Models.

Not measured Not applicable 85 Not measured Not measured Not measured BSD-3-Clause
compressr App New

Model conversion and quantization with no Python: reads SafeTensors, GGUF, TCF and PyTorch state dicts, writes SafeTensors, GGUF and TCF, and quantizes to Q2_K through Q8_0 and IQ4 formats, including Q4_K_M mixes. GPTQ, AWQ, NF4, FP8, EXL2 and ONNX input are not implemented.

Python bindings

23 downloads over 30 days Not applicable 0 0.2.1 GPU support unknown No native code found Apache-2.0
Why FeaturedIt passes every Featured gate.

What it meets

  • It has 331 active dependents and 302 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days.
  • Active dependents are at 100% of their peak. Featured needs at least 50%.
  • Docs are present. The release commit or a manifest ties the crate to the repository.
  • No vulnerability advisory stays unpatched past the grace window. At least one version is neither a prerelease nor 0.0.x.
  • The last activity is on 24 Sep 2026, 46 days ago. The rules expect an update within 800 days. Dormancy rule

Exact rules: Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 1.0.0 base 200, doubled for 3442405 downloads per month, doubled for 330.5 active users: E = 800 days
  • dormancy: last activity 2026-09-24, 46 days ago, E = 800: active
  • featured: featured: active_users 330.5, new_adopters 301.5, former_glory 1

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption331 active dependents, 302 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents330.5crates.io database dumpYes
New dependents (365 days)301.5crates.io database dumpYes
Peak active dependents329crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 46 days ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-09-24GitHub repositoryYes
Latest release2026-07-10crates.io database dumpYes
First release2023-07-19crates.io database dumpYes
Latest version1.0.0crates.io database dumpYes
Days the oldest outside issue waits for a reply412GitHub repositoryYes
Maintainer replies over 365 days2GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution16 releases, 3,442,405 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases16crates.io database dumpYes
Downloads over 30 days3442405crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository343 stars, 143 forks, 28 contributors, 174 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars343GitHub repositoryYes — one part of the repository route
GitHub forks143GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account28GitHub contributorsYes — one part of the repository route
Commits on the default branch174GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseApache-2.0crates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly578crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.