Skip to main content

HFClient

Struct HFClient 

Source
pub struct HFClient { /* private fields */ }
Expand description

Async client for the Hugging Face Hub API.

HFClient wraps an Arc<HFClientInner> so it is cheap to clone — all clones share the same underlying HTTP connection pool, token, and configuration.

§Creating a client

use hf_hub::HFClient;

// Reads token and settings from the environment (HF_TOKEN, HF_ENDPOINT, …).
let client = HFClient::new()?;

// Or configure explicitly:
let client = HFClient::builder().token("hf_…").endpoint("https://huggingface.co").build()?;

Implementations§

Source§

impl HFClient

Source

pub fn new() -> HFResult<Self>

Creates a client with default settings, reading the token and endpoint from the environment. Equivalent to HFClient::builder().build().

§Errors

Fails if the resolved endpoint URL is invalid or the HTTP client cannot be built.

Source

pub fn builder() -> HFClientBuilder

Returns an HFClientBuilder for fine-grained configuration.

Source

pub fn endpoint(&self) -> &str

Hub base URL this client targets, with any trailing slash trimmed.

Resolved at build time from HFClientBuilder::endpointHF_ENDPOINT → the default (https://huggingface.co).

Source

pub fn cache_dir(&self) -> &Path

Local cache directory used for downloaded files.

Resolved at build time from HFClientBuilder::cache_dirHF_HUB_CACHE$HF_HOME/hub~/.cache/huggingface/hub. Returned even when caching is disabled — see cache_enabled to check that.

Source

pub fn cache_enabled(&self) -> bool

Whether the local file cache is enabled. Set via HFClientBuilder::cache_enabled; defaults to true.

Source§

impl HFClient

Source

pub fn bucket( &self, owner: impl Into<String>, name: impl Into<String>, ) -> HFBucket

Create an HFBucket handle for a bucket.

The returned handle is cheap to clone and can be reused across multiple bucket-scoped operations.

Source

pub fn create_bucket<'f1, 'f2, 'f3>( &'f1 self, ) -> HFClientCreateBucketBuilder<'f1, 'f2, 'f3>

Create a new bucket on the Hub. Endpoint: POST /api/buckets/{namespace}/{name}.

When exist_ok is true, an existing bucket is treated as success and a BucketUrl is synthesized locally.

§Parameters
  • namespace (required): namespace (user or organization) that owns the bucket.
  • name (required): bucket name within the namespace.
  • private (default false): whether the bucket should be private.
  • resource_group_id: enterprise resource group ID.
  • exist_ok (default false): if true, do not error when the bucket already exists.
Source

pub fn delete_bucket<'f1, 'f2>( &'f1 self, ) -> HFClientDeleteBucketBuilder<'f1, 'f2>

Delete a bucket from the Hub. Endpoint: DELETE /api/buckets/{bucket_id}.

§Parameters
  • bucket_id (required): bucket ID in "owner/name" format.
  • missing_ok (default false): if true, do not error when the bucket does not exist.
Source

pub fn list_buckets<'f1>(&'f1 self) -> HFClientListBucketsBuilder<'f1>

List buckets in a namespace.

Streams bucket metadata for all buckets owned by the given user or organization.

Endpoint: GET /api/buckets/{namespace} (paginated).

§Parameters
  • namespace (required): user or organization namespace to list buckets for.
Source

pub fn move_bucket<'f1, 'f2, 'f3>( &'f1 self, ) -> HFClientMoveBucketBuilder<'f1, 'f2, 'f3>

Move (rename) a bucket.

Endpoint: POST /api/repos/move with type: "bucket".

§Parameters
  • from_id (required): current bucket ID in "owner/name" format.
  • to_id (required): new bucket ID in "owner/name" format.
Source§

impl HFClient

Source

pub fn scan_cache<'f1>(&'f1 self) -> HFClientScanCacheBuilder<'f1>

Available on non-target_family=wasm only.

Scan the configured cache directory and return a summary of all cached repositories, revisions, and files.

If the cache directory does not exist, returns an HFCacheInfo with no repos and zero size — not an error. Unreadable blobs and dangling snapshot pointers are reported via HFCacheInfo::warnings rather than failing the scan.

Source§

impl HFClient

Source

pub fn repository<T: RepoType>( &self, repo_type: T, owner: impl Into<String>, name: impl Into<String>, ) -> HFRepository<T>

Create an HFRepository handle for any repo kind via a turbofished generic.

Equivalent to the typed shortcuts (model, dataset, space, kernel) but useful when the kind is expressed by an external type parameter or a match arm — for example, dispatching from a CLI flag:

let repo = client.repository(RepoTypeDataset, "rajpurkar", "squad");
Source

pub fn model( &self, owner: impl Into<String>, name: impl Into<String>, ) -> HFRepository<RepoTypeModel>

Create an HFRepository handle for a model repository.

Source

pub fn dataset( &self, owner: impl Into<String>, name: impl Into<String>, ) -> HFRepository<RepoTypeDataset>

Create an HFRepository handle for a dataset repository.

Source

pub fn space( &self, owner: impl Into<String>, name: impl Into<String>, ) -> HFRepository<RepoTypeSpace>

Create an HFRepository handle for a Space repository.

Source

pub fn kernel( &self, owner: impl Into<String>, name: impl Into<String>, ) -> HFRepository<RepoTypeKernel>

Create an HFRepository handle for a kernel repository.

Source§

impl HFClient

Source

pub fn list_models<'f1>(&'f1 self) -> HFClientListModelsBuilder<'f1>

List models on the Hub. Endpoint: GET /api/models.

Returns a stream of ModelInfo entries. Pagination is automatic.

§Parameters
  • search: free-text query forwarded as the ?search= parameter. The Hub matches it substring-style against the model id and (when present) the model card description — it is not a tag filter.
  • author: namespace owner to filter on, forwarded as ?author=. Pass a Hub user or organization name (e.g., "google", "meta-llama") — bare names, not paths.
  • filter: a single Hub tag value forwarded as ?filter=. Tags use the Hub’s namespaced format, e.g., "pytorch", "text-generation", "license:apache-2.0", "language:en", "dataset:wikipedia", "region:us". To combine tags, narrow the results client-side (only one filter value is sent).
  • sort: API field name to sort by, forwarded as ?sort=. Common values are "downloads", "likes", "createdAt", "lastModified", and "trendingScore". Use the camelCase Hub field names (not Rust struct field names).
  • pipeline_tag: pipeline-tag filter (e.g., "text-classification", "automatic-speech-recognition"), forwarded as ?pipeline_tag=. Same vocabulary as the pipeline_tag field on a model card.
  • full: fetch the full model information including all fields.
  • card_data: include the model card metadata in the response.
  • fetch_config: include the model configuration in the response.
  • limit: cap on the total number of items yielded by the stream. When less than 1000, also used as the server page size.
Source

pub fn list_datasets<'f1>(&'f1 self) -> HFClientListDatasetsBuilder<'f1>

List datasets on the Hub. Endpoint: GET /api/datasets.

Returns a stream of DatasetInfo entries. Pagination is automatic.

§Parameters
  • search: free-text query forwarded as ?search=. The Hub matches it substring-style against the dataset id and card description — not a tag filter.
  • author: namespace owner forwarded as ?author=. Pass a bare Hub user or organization name (e.g., "HuggingFaceH4", "allenai").
  • filter: a single Hub tag value forwarded as ?filter=. Tags use the Hub’s namespaced format, e.g., "task_categories:text-classification", "language:en", "size_categories:10K<n<100K", "license:mit". To combine tags, narrow client-side — only one filter value is sent.
  • sort: API field name to sort by, forwarded as ?sort=. Common values are "downloads", "likes", "createdAt", "lastModified", and "trendingScore" (Hub camelCase field names).
  • full: fetch the full dataset information including all fields.
  • limit: cap on the total number of items yielded by the stream. When less than 1000, also used as the server page size.
Source

pub fn list_spaces<'f1>(&'f1 self) -> HFClientListSpacesBuilder<'f1>

List Spaces on the Hub. Endpoint: GET /api/spaces.

Returns a stream of SpaceInfo entries. Pagination is automatic.

§Parameters
  • search: free-text query forwarded as ?search=. The Hub matches it substring-style against the Space id and card description — not a tag filter.
  • author: namespace owner forwarded as ?author=. Pass a bare Hub user or organization name (e.g., "openai", "stabilityai").
  • filter: a single Hub tag value forwarded as ?filter=. Tags use the Hub’s namespaced format, e.g., "sdk:gradio", "sdk:streamlit", "sdk:docker", "language:en", "license:mit". To combine tags, narrow client-side — only one filter value is sent.
  • sort: API field name to sort by, forwarded as ?sort=. Common values are "likes", "createdAt", "lastModified", and "trendingScore" (Hub camelCase field names).
  • full: fetch the full Space information including all fields.
  • limit: cap on the total number of items yielded by the stream. When less than 1000, also used as the server page size.
Source

pub fn create_repository<'f1, 'f2, I1>( &'f1 self, ) -> HFClientCreateRepositoryBuilder<'f1, 'f2, I1>
where I1: RepoType,

Create a new repository. Endpoint: POST /api/repos/create.

The repo kind is picked at the call site by passing one of the four marker structs to repo_type — e.g., client.create_repository().repo_type(RepoTypeDataset)... to create a dataset. The body always includes the type field, matching the Hub’s per-kind defaults.

§Parameters
  • repo_id (required): repository ID in "owner/name" or "name" format.
  • repo_type (required): the repo kind (RepoTypeModel, RepoTypeDataset, RepoTypeSpace, or RepoTypeKernel).
  • private: whether the repository should be private.
  • exist_ok (default false): if true, do not error when the repository already exists.
  • space_sdk: SDK for a Space (e.g., "gradio", "streamlit", "docker"). Required when repo_type is RepoTypeSpace; ignored for other repo kinds.
Source

pub fn delete_repository<'f1, 'f2, I1>( &'f1 self, ) -> HFClientDeleteRepositoryBuilder<'f1, 'f2, I1>
where I1: RepoType,

Delete a repository. Endpoint: DELETE /api/repos/delete.

The repo kind is picked at the call site by passing one of the four marker structs to repo_type — e.g., client.delete_repository().repo_type(RepoTypeSpace).... The body always includes the type field.

§Parameters
Source

pub fn move_repository<'f1, 'f2, 'f3, I1>( &'f1 self, ) -> HFClientMoveRepositoryBuilder<'f1, 'f2, 'f3, I1>
where I1: RepoType,

Move (rename) a repository. Endpoint: POST /api/repos/move.

The repo kind is picked at the call site by passing one of the four marker structs to repo_type — e.g., client.move_repository().repo_type(RepoTypeModel).... The body always includes the type field.

§Parameters
Source§

impl HFClient

Source

pub fn whoami<'f1>(&'f1 self) -> HFClientWhoamiBuilder<'f1>

Fetch the profile of the user that owns the current token.

Returns the authenticated User, including private fields like email and the caller’s orgs list. Fails with HFError::AuthRequired if no valid token is configured.

Endpoint: GET /api/whoami-v2.

Source

pub fn user_overview<'f1, 'f2>( &'f1 self, ) -> HFClientUserOverviewBuilder<'f1, 'f2>

Fetch the public profile of a user by Hub handle.

Endpoint: GET /api/users/{username}/overview.

§Parameters
  • username (required): Hub handle (slug) of the user.
Source

pub fn organization_overview<'f1, 'f2>( &'f1 self, ) -> HFClientOrganizationOverviewBuilder<'f1, 'f2>

Fetch the public profile of an organization by Hub handle.

Endpoint: GET /api/organizations/{organization}/overview.

§Parameters
  • organization (required): Hub handle (slug) of the organization.
Source

pub fn list_user_followers<'f1>( &'f1 self, ) -> HFClientListUserFollowersBuilder<'f1>

Stream the followers of a user.

Endpoint: GET /api/users/{username}/followers.

§Parameters
  • username (required): Hub handle of the user.
  • limit: cap on the total number of items yielded.
Source

pub fn list_user_following<'f1>( &'f1 self, ) -> HFClientListUserFollowingBuilder<'f1>

Stream the users that a user is following.

Endpoint: GET /api/users/{username}/following.

§Parameters
  • username (required): Hub handle of the user.
  • limit: cap on the total number of items yielded.
Source

pub fn list_organization_members<'f1>( &'f1 self, ) -> HFClientListOrganizationMembersBuilder<'f1>

Stream the members of an organization.

Endpoint: GET /api/organizations/{organization}/members.

§Parameters
  • organization (required): Hub handle of the organization.
  • limit: cap on the total number of items yielded.

Trait Implementations§

Source§

impl Clone for HFClient

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HFClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DropFlavorWrapper<T> for T

Source§

type Flavor = MayDrop

The DropFlavor that wraps T into Self
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<E> ResultError for E
where E: Send + Debug + Sync,

Source§

impl<T> ResultType for T
where T: Send + Clone + Sync + Debug,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more