Skip to main content

ApiClient

Struct ApiClient 

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

Handles API requests with authentication.

§Example

use xurl::api::{ApiClient, RequestOptions, RequestTarget};
use xurl::auth::Auth;
use xurl::config::Config;
use xurl::error::XurlError;
use std::collections::HashMap;

let cfg = Config::new();
let auth = Auth::new(&cfg);
let mut client = ApiClient::new(&cfg, auth);

let mut opts = RequestOptions::default();
opts.method = "GET".to_string();
opts.target = RequestTarget::Template {
    path: "/2/users/me".to_string(),
    path_params: HashMap::new(),
    query: Vec::new(),
};

match client.send_request(&opts) {
    Ok(json) => println!("{json}"),
    Err(XurlError::Api { status, body }) => eprintln!("API {status}: {body}"),
    Err(e) => eprintln!("error: {e}"),
}

Implementations§

Source§

impl ApiClient

Source

pub fn new(config: &Config, auth: Auth) -> Self

Creates a new ApiClient using the timeout configured on config.

The CLI runner writes --timeout / XURL_TIMEOUT into Config::http_timeout_secs; library consumers that want a different timeout can use ApiClient::with_timeout.

Source

pub fn with_timeout(config: &Config, auth: Auth, timeout_secs: u64) -> Self

Creates a new ApiClient with an explicit request timeout.

The timeout bounds every non-streaming HTTP call dispatched by this client. Streaming requests intentionally retain .timeout(None) — the long-running shape is the point — and bound runtime via signal handlers in the streaming handler.

Source

pub fn timeout_secs(&self) -> u64

Returns the per-call timeout used by this client (seconds).

Source

pub fn set_output(&mut self, out: OutputConfig)

Installs an OutputConfig for verbose request/response diagnostics.

The CLI runner calls this after constructing the client so the verbose logs route through the single output owner. Library callers that skip this get a default config (text, verbose off).

Source

pub fn from_env() -> Result<Self>

Creates an ApiClient from environment variables.

Reads CLIENT_ID, CLIENT_SECRET, and other env vars via Config::new(), validates that CLIENT_ID is non-empty, and returns a ready-to-use client.

For full control over configuration and auth, use ApiClient::new() instead.

§Errors

Returns XurlError::Validation if CLIENT_ID is not set or empty.

Source

pub fn build_url_public(&self, target: &RequestTarget) -> Result<String>

Builds the full URL from a target (public accessor for command layer).

§Errors

Returns XurlError::InvalidUrl when a RawUrl target’s scheme is not http or https, XurlError::InvalidPathParam when a substituted value contains a URL-reserved character, or XurlError::Internal when a path template references a {name} segment missing from path_params.

Source

pub fn auth_app_name(&self) -> &str

Returns the active app name carried by the underlying Auth.

Library-public so callers building requests outside ApiClient (e.g. the CLI streaming wrapper) can thread the active app into auth_matrix::validate for the user-facing message.

Source

pub fn send_request(&mut self, options: &RequestOptions) -> Result<Value>

Sends a regular API request and returns the JSON response.

§Errors

Returns an error if the HTTP method is invalid, the request fails, or the API returns an error status (>= 400).

Source

pub fn send_multipart_request( &mut self, options: &MultipartOptions, ) -> Result<Value>

Sends a multipart request (used for media upload chunks).

§Errors

Returns an error if the HTTP method is invalid, file I/O fails, the request fails, or the API returns an error status (>= 400).

Source

pub fn stream_request( &mut self, options: &RequestOptions, stdout: &mut dyn Write, stderr: &mut dyn Write, ) -> Result<()>

Sends a streaming request — reads lines until EOF.

All output flows through this client’s configured OutputConfig (set via ApiClient::set_output); the CLI binary calls the stream_request_with_output helper in cli::commands which threads the runner’s OutputConfig and writers in directly. Library callers pass their own stdout/stderr here so a streaming session can be captured in tests or redirected to a custom sink.

§Errors

Returns an error if the HTTP method is invalid, the request fails, the API returns an error status (>= 400), or a read error occurs.

Source

pub fn get_auth_header_public( &mut self, options: &RequestOptions, ) -> Result<String>

Gets the authorization header for a request (public accessor for command layer).

§Errors

Returns an error if no valid auth method is found, or — when the auto-detect path resolves an empty intersection between stored credentials and the endpoint’s accepted schemes — an XurlError::AuthMethodMismatch in the empty-intersection shape.

Source§

impl ApiClient

Source

pub fn create_post( &mut self, text: &str, media_ids: &[String], opts: &CallOptions, ) -> Result<ApiResponse<Tweet>>

Creates a new post.

§Errors

Returns an error if the request fails or the API returns an error.

§Example
use xurl::api::{ApiClient, CallOptions};
use xurl::auth::Auth;
use xurl::config::Config;

let cfg = Config::new();
let auth = Auth::new(&cfg);
let mut client = ApiClient::new(&cfg, auth);

let resp = client.create_post("hello from xurl", &[], &CallOptions::default())?;
println!("created post id={}", resp.data.id);
Source

pub fn reply_to_post( &mut self, post_id: &str, text: &str, media_ids: &[String], opts: &CallOptions, ) -> Result<ApiResponse<Tweet>>

Replies to an existing post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn quote_post( &mut self, post_id: &str, text: &str, opts: &CallOptions, ) -> Result<ApiResponse<Tweet>>

Quotes an existing post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn delete_post( &mut self, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<DeletedResult>>

Deletes a post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn read_post( &mut self, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<Tweet>>

Reads a single post with expansions.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn search_posts( &mut self, query: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<Tweet>>>

Searches recent posts.

§Errors

Returns an error if the request fails or the API returns an error.

§Example
use xurl::api::{ApiClient, CallOptions};
use xurl::auth::Auth;
use xurl::config::Config;

let cfg = Config::new();
let auth = Auth::new(&cfg);
let mut client = ApiClient::new(&cfg, auth);

let resp = client.search_posts("rustlang", 25, &CallOptions::default())?;
for tweet in &resp.data {
    println!("{}: {}", tweet.id, tweet.text);
}
Source

pub fn get_me(&mut self, opts: &CallOptions) -> Result<ApiResponse<User>>

Fetches the authenticated user’s profile.

§Errors

Returns an error if the request fails or the API returns an error.

§Example
use xurl::api::{ApiClient, CallOptions};
use xurl::auth::Auth;
use xurl::config::Config;

let cfg = Config::new();
let auth = Auth::new(&cfg);
let mut client = ApiClient::new(&cfg, auth);

let resp = client.get_me(&CallOptions::default())?;
println!("@{} ({})", resp.data.username, resp.data.id);
Source

pub fn lookup_user( &mut self, username: &str, opts: &CallOptions, ) -> Result<ApiResponse<User>>

Looks up a user by username.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_timeline( &mut self, user_id: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<Tweet>>>

Fetches the home timeline.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_mentions( &mut self, user_id: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<Tweet>>>

Fetches recent mentions.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn like_post( &mut self, user_id: &str, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<LikedResult>>

Likes a post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn unlike_post( &mut self, user_id: &str, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<LikedResult>>

Unlikes a post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn repost( &mut self, user_id: &str, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<RetweetedResult>>

Reposts a post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn unrepost( &mut self, user_id: &str, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<RetweetedResult>>

Removes a repost.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn bookmark( &mut self, user_id: &str, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<BookmarkedResult>>

Bookmarks a post.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn unbookmark( &mut self, user_id: &str, post_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<BookmarkedResult>>

Removes a bookmark.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_bookmarks( &mut self, user_id: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<Tweet>>>

Fetches bookmarks.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn follow_user( &mut self, source_user_id: &str, target_user_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<FollowingResult>>

Follows a user.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn unfollow_user( &mut self, source_user_id: &str, target_user_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<FollowingResult>>

Unfollows a user.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_following( &mut self, user_id: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<User>>>

Fetches users that a given user follows.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_followers( &mut self, user_id: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<User>>>

Fetches followers of a given user.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn send_dm( &mut self, participant_id: &str, text: &str, opts: &CallOptions, ) -> Result<ApiResponse<DmEvent>>

Sends a direct message.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_dm_events( &mut self, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<DmEvent>>>

Fetches recent DM events.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_liked_posts( &mut self, user_id: &str, max_results: i32, opts: &CallOptions, ) -> Result<ApiResponse<Vec<Tweet>>>

Fetches posts liked by a user.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn mute_user( &mut self, source_user_id: &str, target_user_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<MutingResult>>

Mutes a user.

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn get_usage( &mut self, opts: &CallOptions, ) -> Result<ApiResponse<UsageData>>

Fetches API usage data (tweet caps, daily breakdowns).

§Errors

Returns an error if the request fails or the API returns an error.

Source

pub fn unmute_user( &mut self, source_user_id: &str, target_user_id: &str, opts: &CallOptions, ) -> Result<ApiResponse<MutingResult>>

Unmutes a user.

§Errors

Returns an error if the request fails or the API returns an error.

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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<T> Same for T

Source§

type Output = T

Should always be Self
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