ApiClientBuilder

Struct ApiClientBuilder 

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

Builder for creating ApiClient instances with comprehensive configuration options.

ApiClientBuilder provides a fluent interface for configuring all aspects of an API client, including network settings, base paths, OpenAPI metadata, and server definitions.

§Default Configuration

  • Scheme: HTTP (use with_scheme() to change to HTTPS)
  • Host: 127.0.0.1 (localhost)
  • Port: 80 (standard HTTP port)
  • Base path: None (requests go to root path)
  • OpenAPI info: None (no metadata)
  • Servers: Empty list

§Example

use clawspec_core::ApiClient;
use http::uri::Scheme;
use utoipa::openapi::{InfoBuilder, ServerBuilder};

let client = ApiClient::builder()
    .with_scheme(Scheme::HTTPS)
    .with_host("api.example.com")
    .with_port(443)
    .with_base_path("/v1")?
    .with_info(
        InfoBuilder::new()
            .title("Example API")
            .version("1.0.0")
            .description(Some("API documentation generated from tests"))
            .build()
    )
    .add_server(
        ServerBuilder::new()
            .url("https://api.example.com/v1")
            .description(Some("Production server"))
            .build()
    )
    .add_server(
        ServerBuilder::new()
            .url("https://staging.example.com/v1")
            .description(Some("Staging server"))
            .build()
    )
    .build()?;

Implementations§

Source§

impl ApiClientBuilder

Source

pub fn build(self) -> Result<ApiClient, ApiClientError>

Builds the final ApiClient instance with all configured settings.

This method consumes the builder and creates an ApiClient ready for making API calls. All configuration options set through the builder methods are applied to the client.

§Returns

Returns a Result<ApiClient, ApiClientError> which will be:

  • Ok(ApiClient) if the client was created successfully
  • Err(ApiClientError) if there was an error building the URI or other configuration issues
§Errors

This method can fail if:

  • The base URI cannot be constructed from the provided scheme, host, and port
  • The base path is invalid and cannot be parsed
§Example
use clawspec_core::ApiClient;

let client = ApiClient::builder()
    .with_host("api.example.com")
    .with_base_path("/v1")?
    .build()?;  // This consumes the builder

// Now you can use the client for API calls
Source

pub fn with_scheme(self, scheme: Scheme) -> Self

Sets the HTTP scheme. Defaults to HTTP. Use with_https() for convenience.

Source

pub fn with_host(self, host: impl Into<String>) -> Self

Sets the hostname or IP address. Defaults to 127.0.0.1.

Source

pub fn with_port(self, port: u16) -> Self

Sets the port number. Defaults to 80.

Source

pub fn with_base_path<P>(self, base_path: P) -> Result<Self, ApiClientError>
where P: TryInto<PathAndQuery>, P::Error: Debug + 'static,

Sets the base path prepended to all requests (e.g., /v1 or /api/v2).

§Errors

Returns ApiClientError::InvalidBasePath if the path is invalid.

Source

pub fn with_info(self, info: Info) -> Self

Sets the OpenAPI info metadata (title, version, description, etc.).

Use with_info_simple() for basic cases.

Source

pub fn with_servers(self, servers: Vec<Server>) -> Self

Sets the OpenAPI servers list. Use add_server() to add incrementally.

Source

pub fn add_server(self, server: Server) -> Self

Adds a server to the OpenAPI specification. Use add_server_simple() for convenience.

Source

pub fn with_authentication(self, authentication: Authentication) -> Self

Sets the default authentication for all requests. Can be overridden per-request.

Supports Bearer, Basic, and ApiKey authentication types.

Source

pub fn with_info_simple( self, title: impl Into<String>, version: impl Into<String>, ) -> Self

Convenience method to set API title and version without importing utoipa types.

Source

pub fn with_description(self, description: impl Into<String>) -> Self

Sets or updates the API description. Creates default info if not set.

Source

pub fn with_https(self) -> Self

Sets the HTTP scheme to HTTPS. Convenience method for with_scheme(Scheme::HTTPS).

Source

pub fn add_server_simple( self, url: impl Into<String>, description: impl Into<String>, ) -> Self

Adds a server with URL and description. No utoipa imports needed.

Source

pub fn with_security_scheme( self, name: impl Into<String>, scheme: SecurityScheme, ) -> Self

Registers a named security scheme for OpenAPI components.securitySchemes.

Source

pub fn with_default_security(self, requirement: SecurityRequirement) -> Self

Sets the default security requirement for all operations.

Source

pub fn with_default_securities( self, requirements: impl IntoIterator<Item = SecurityRequirement>, ) -> Self

Adds multiple default security requirements (OR relationship).

Source

pub fn with_oauth2_client_credentials( self, client_id: impl Into<String>, client_secret: impl Into<SecureString>, token_url: impl AsRef<str>, ) -> Result<Self, ApiClientError>

Available on crate feature oauth2 only.

Configures OAuth2 Client Credentials authentication. Tokens are auto-refreshed.

§Errors

Returns an error if the token URL is invalid.

let client = ApiClient::builder()
    .with_oauth2_client_credentials("client-id", "secret", "https://auth.example.com/token")?
    .build()?;
Source

pub fn with_oauth2_client_credentials_scopes( self, client_id: impl Into<String>, client_secret: impl Into<SecureString>, token_url: impl AsRef<str>, scopes: impl IntoIterator<Item = impl Into<String>>, ) -> Result<Self, ApiClientError>

Available on crate feature oauth2 only.

Configures OAuth2 authentication with Client Credentials flow and scopes.

This is a convenience method for setting up OAuth2 authentication with specific scopes.

§Parameters
  • client_id - The OAuth2 client ID
  • client_secret - The OAuth2 client secret
  • token_url - The token endpoint URL
  • scopes - The OAuth2 scopes to request
§Example
use clawspec_core::ApiClient;

let client = ApiClient::builder()
    .with_oauth2_client_credentials_scopes(
        "my-client-id",
        "my-client-secret",
        "https://auth.example.com/oauth/token",
        ["read:users", "write:users"],
    )?
    .build()?;
Source

pub fn with_oauth2_token( self, access_token: impl Into<String>, ) -> Result<Self, ApiClientError>

Available on crate feature oauth2 only.

Configures OAuth2 authentication with a pre-acquired token.

Use this method when you already have an access token from another source (e.g., environment variable, test setup).

§Parameters
  • access_token - The pre-acquired access token
§Example
use clawspec_core::ApiClient;

let token = std::env::var("API_TOKEN").unwrap_or_else(|_| "test-token".to_string());

let client = ApiClient::builder()
    .with_oauth2_token(token)?
    .build()?;

Trait Implementations§

Source§

impl Clone for ApiClientBuilder

Source§

fn clone(&self) -> ApiClientBuilder

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ApiClientBuilder

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for ApiClientBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. 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> 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: 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: 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> 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