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 (protocol) for the API client.

§Parameters
  • scheme - The HTTP scheme to use (HTTP or HTTPS)
§Default

If not specified, defaults to Scheme::HTTP.

§Example
use clawspec_core::ApiClient;
use http::uri::Scheme;

let client = ApiClient::builder()
    .with_scheme(Scheme::HTTPS)  // Use HTTPS for secure connections
    .with_host("api.example.com")
    .build()?;
Source

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

Sets the hostname for the API client.

§Parameters
  • host - The hostname or IP address of the API server
§Default

If not specified, defaults to "127.0.0.1" (localhost).

§Example
use clawspec_core::ApiClient;

let client = ApiClient::builder()
    .with_host("api.example.com")     // Domain name
    .build()?;

let client = ApiClient::builder()
    .with_host("192.168.1.10")       // IP address
    .build()?;

let client = ApiClient::builder()
    .with_host("localhost")          // Local development
    .build()?;
Source

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

Sets the port number for the API client.

§Parameters
  • port - The port number to connect to on the server
§Default

If not specified, defaults to 80 (standard HTTP port).

§Example
use clawspec_core::ApiClient;
use http::uri::Scheme;

let client = ApiClient::builder()
    .with_scheme(Scheme::HTTPS)
    .with_host("api.example.com")
    .with_port(443)              // Standard HTTPS port
    .build()?;

let client = ApiClient::builder()
    .with_host("localhost")
    .with_port(8080)             // Common development port
    .build()?;
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 for all API requests.

This path will be prepended to all request paths. The path must be valid according to URI standards (no spaces, properly encoded, etc.).

§Examples
use clawspec_core::ApiClient;

// API versioning
let client = ApiClient::builder()
    .with_host("api.example.com")
    .with_base_path("/v1")?              // All requests will start with /v1
    .build()?;

// More complex base paths
let client = ApiClient::builder()
    .with_base_path("/api/v2")?          // Multiple path segments
    .build()?;

// Nested API paths
let client = ApiClient::builder()
    .with_base_path("/services/user-api/v1")?  // Deep nesting
    .build()?;
§Errors

Returns ApiClientError::InvalidBasePath if the path contains invalid characters (such as spaces) or cannot be parsed as a valid URI path.

Source

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

Sets the OpenAPI info metadata for the generated specification.

The info object provides metadata about the API including title, version, description, contact information, license, and other details that will appear in the generated OpenAPI specification.

§Parameters
  • info - The OpenAPI Info object containing API metadata
§Example
use clawspec_core::ApiClient;
use utoipa::openapi::InfoBuilder;

let client = ApiClient::builder()
    .with_info(
        InfoBuilder::new()
            .title("My API")
            .version("1.0.0")
            .description(Some("A comprehensive API for managing resources"))
            .build()
    )
    .build()?;
§Notes
  • If no info is set, the generated OpenAPI specification will not include an info section
  • The info can be updated by calling this method multiple times (last call wins)
  • Common practice is to set at least title and version for OpenAPI compliance
Source

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

Sets the complete list of servers for the OpenAPI specification.

This method replaces any previously configured servers. Use add_server() if you want to add servers incrementally.

§Parameters
  • servers - A vector of Server objects defining the available API servers
§Example
use clawspec_core::ApiClient;
use utoipa::openapi::ServerBuilder;

let servers = vec![
    ServerBuilder::new()
        .url("https://api.example.com/v1")
        .description(Some("Production server"))
        .build(),
    ServerBuilder::new()
        .url("https://staging.example.com/v1")
        .description(Some("Staging server"))
        .build(),
];

let client = ApiClient::builder()
    .with_servers(servers)
    .build()?;
Source

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

Adds a single server to the OpenAPI specification.

This method allows you to incrementally add servers to the configuration. Each call adds to the existing list of servers.

§Parameters
  • server - A Server object defining an available API server
§Example
use clawspec_core::ApiClient;
use utoipa::openapi::ServerBuilder;

let client = ApiClient::builder()
    .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()
    )
    .add_server(
        ServerBuilder::new()
            .url("http://localhost:8080")
            .description(Some("Development server"))
            .build()
    )
    .build()?;
§Server Definition Best Practices
  • Include meaningful descriptions for each server
  • Order servers by preference (production first, then staging, then development)
  • Use HTTPS for production servers when available
  • Include the full base URL including API version paths
Source

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

Sets the authentication configuration for the API client.

This authentication will be applied to all requests made by the client, unless overridden on a per-request basis.

§Examples
use clawspec_core::{ApiClient, Authentication};

// Bearer token authentication
let client = ApiClient::builder()
    .with_authentication(Authentication::Bearer("my-api-token".into()))
    .build()?;

// Basic authentication
let client = ApiClient::builder()
    .with_authentication(Authentication::Basic {
        username: "user".to_string(),
        password: "pass".into(),
    })
    .build()?;

// API key authentication
let client = ApiClient::builder()
    .with_authentication(Authentication::ApiKey {
        header_name: "X-API-Key".to_string(),
        key: "secret-key".into(),
    })
    .build()?;
§Authentication Types
  • Bearer: Adds Authorization: Bearer <token> header
  • Basic: Adds Authorization: Basic <base64(username:password)> header
  • ApiKey: Adds custom header with API key
§Security Considerations
  • Authentication credentials are stored in memory and may be logged
  • Use secure token storage and rotation practices
  • Avoid hardcoding credentials in source code
  • Consider using environment variables or secure vaults

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<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
Source§

impl<T> ErasedDestructor for T
where T: 'static,