CallResult

Struct CallResult 

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

Represents the result of an API call with response processing capabilities.

This struct contains the response from an HTTP request along with methods to process the response in various formats (JSON, text, bytes, etc.) while automatically collecting OpenAPI schema information.

§⚠️ Important: Response Consumption Required

You must consume this CallResult by calling one of the response processing methods to ensure proper OpenAPI documentation generation. Simply calling exchange() and not processing the result will result in incomplete OpenAPI specifications.

§Required Response Processing

Choose the appropriate method based on your expected response:

§Example: Correct Usage

use clawspec_core::ApiClient;

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

// ✅ CORRECT: Always consume the CallResult
let user: User = client
    .get("/users/123")?

    .await?
    .as_json()  // ← This is required!
    .await?;

// ✅ CORRECT: For empty responses (like DELETE)
client
    .delete("/users/123")?

    .await?
    .as_empty()  // ← This is required!
    .await?;

// ❌ INCORRECT: This will not generate proper OpenAPI documentation
// let _result = client.get("/users/123")?.await?;
// // Missing .as_json() or other consumption method! This will not generate proper OpenAPI documentation

§Why This Matters

The OpenAPI schema generation relies on observing how responses are processed. Without calling a consumption method:

  • Response schemas won’t be captured
  • Content-Type information may be incomplete
  • Operation examples won’t be generated
  • The resulting OpenAPI spec will be missing crucial response documentation

Implementations§

Source§

impl CallResult

Source

pub async fn as_json_redacted<T>( &mut self, ) -> Result<RedactionBuilder<T>, ApiClientError>
where T: DeserializeOwned + ToSchema + 'static,

Available on crate feature redaction only.

Deserializes the JSON response and returns a builder for applying redactions.

This method is similar to as_json() but returns a RedactionBuilder that allows you to apply redactions to the JSON before finalizing the result.

The original value is preserved for test assertions, while the redacted JSON can be used for snapshot testing with stable values.

§Type Parameters
§Errors

Returns an error if:

  • The response is not JSON
  • JSON deserialization fails
§Example
let result = client
    .get("/api/users/123")?
    .await?
    .as_json_redacted::<User>().await?
    .redact("/id", "stable-uuid")?
    .finish()
    .await;

// Use real value for assertions
assert!(!result.value.id.is_empty());

// Use redacted value for snapshots
insta::assert_yaml_snapshot!(result.redacted);
Source§

impl CallResult

Source

pub async fn as_json<T>(&mut self) -> Result<T, ApiClientError>
where T: DeserializeOwned + ToSchema + 'static,

Processes the response as JSON and deserializes it to the specified type.

This method automatically records the response schema in the OpenAPI specification and processes the response body as JSON. The type parameter must implement DeserializeOwned and ToSchema for proper JSON parsing and schema generation.

§Type Parameters
  • T: The target type for deserialization, must implement DeserializeOwned, ToSchema, and 'static
§Returns
  • Ok(T): The deserialized response object
  • Err(ApiClientError): If the response is not JSON or deserialization fails
§Example
#[derive(Deserialize, ToSchema)]
struct User {
    id: u32,
    name: String,
}

let mut client = ApiClient::builder().build()?;
let user: User = client
    .get("/users/123")?

    .await?
    .as_json()
    .await?;
Source

pub async fn as_optional_json<T>(&mut self) -> Result<Option<T>, ApiClientError>
where T: DeserializeOwned + ToSchema + 'static,

Processes the response as optional JSON, treating 204 and 404 status codes as None.

This method provides ergonomic handling of optional REST API responses by automatically treating 204 (No Content) and 404 (Not Found) status codes as None, while deserializing other successful responses as Some(T). This is particularly useful for APIs that use HTTP status codes to indicate the absence of data rather than errors.

The method automatically records the response schema in the OpenAPI specification, maintaining proper documentation generation.

§Type Parameters
  • T: The target type for deserialization, must implement DeserializeOwned, ToSchema, and 'static
§Returns
  • Ok(None): If the status code is 204 or 404
  • Ok(Some(T)): The deserialized response object for other successful responses
  • Err(ApiClientError): If the response is not JSON or deserialization fails
§Example
#[derive(Deserialize, ToSchema)]
struct User {
    id: u32,
    name: String,
}

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

// Returns None for 404
let user: Option<User> = client
    .get("/users/nonexistent")?

    .await?
    .as_optional_json()
    .await?;
assert!(user.is_none());

// Returns Some(User) for successful response
let user: Option<User> = client
    .get("/users/123")?

    .await?
    .as_optional_json()
    .await?;
assert!(user.is_some());
Source

pub async fn as_result_json<T, E>( &mut self, ) -> Result<Result<T, E>, ApiClientError>
where T: DeserializeOwned + ToSchema + 'static, E: DeserializeOwned + ToSchema + 'static,

Processes the response as a Result<T, E> based on HTTP status code.

This method provides type-safe error handling for REST APIs that return structured error responses. It automatically deserializes the response body to either the success type T (for 2xx status codes) or the error type E (for 4xx/5xx status codes).

Both success and error schemas are automatically recorded in the OpenAPI specification, providing complete documentation of your API’s response patterns.

§Type Parameters
  • T: The success response type, must implement DeserializeOwned, ToSchema, and 'static
  • E: The error response type, must implement DeserializeOwned, ToSchema, and 'static
§Returns
  • Ok(T): The deserialized success response for 2xx status codes
  • Err(E): The deserialized error response for 4xx/5xx status codes
§Errors

Returns ApiClientError if:

  • The response is not JSON
  • JSON deserialization fails for either type
  • The response body is empty when content is expected
§Example
#[derive(Deserialize, ToSchema)]
struct User {
    id: u32,
    name: String,
}

#[derive(Deserialize, ToSchema)]
struct ApiError {
    code: String,
    message: String,
}

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

// Returns Ok(User) for 2xx responses
let result: Result<User, ApiError> = client
    .get("/users/123")?

    .await?
    .as_result_json()
    .await?;

match result {
    Ok(user) => println!("User: {}", user.name),
    Err(err) => println!("Error: {} - {}", err.code, err.message),
}
Source

pub async fn as_result_option_json<T, E>( &mut self, ) -> Result<Result<Option<T>, E>, ApiClientError>
where T: DeserializeOwned + ToSchema + 'static, E: DeserializeOwned + ToSchema + 'static,

Processes the response as a Result<Option<T>, E> based on HTTP status code.

This method combines optional response handling with type-safe error handling, providing comprehensive support for REST APIs that:

  • Return structured error responses for failures (4xx/5xx)
  • Use 204 (No Content) or 404 (Not Found) to indicate absence of data
  • Return data for other successful responses (2xx)

Both success and error schemas are automatically recorded in the OpenAPI specification.

§Type Parameters
  • T: The success response type, must implement DeserializeOwned, ToSchema, and 'static
  • E: The error response type, must implement DeserializeOwned, ToSchema, and 'static
§Returns
  • Ok(None): For 204 (No Content) or 404 (Not Found) status codes
  • Ok(Some(T)): The deserialized success response for other 2xx status codes
  • Err(E): The deserialized error response for 4xx/5xx status codes
§Errors

Returns ApiClientError if:

  • The response is not JSON (when content is expected)
  • JSON deserialization fails for either type
§Example
#[derive(Deserialize, ToSchema)]
struct User {
    id: u32,
    name: String,
}

#[derive(Deserialize, ToSchema)]
struct ApiError {
    code: String,
    message: String,
}

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

// Returns Ok(None) for 404
let result: Result<Option<User>, ApiError> = client
    .get("/users/nonexistent")?

    .await?
    .as_result_option_json()
    .await?;

match result {
    Ok(Some(user)) => println!("User: {}", user.name),
    Ok(None) => println!("User not found"),
    Err(err) => println!("Error: {} - {}", err.code, err.message),
}
Source

pub async fn as_text(&mut self) -> Result<&str, ApiClientError>

Processes the response as plain text.

This method records the response in the OpenAPI specification and returns the response body as a string slice. The response must have a text content type.

§Returns
  • Ok(&str): The response body as a string slice
  • Err(ApiClientError): If the response is not text
§Example
let mut client = ApiClient::builder().build()?;
let text = client
    .get("/api/status")?

    .await?
    .as_text()
    .await?;
Source

pub async fn as_bytes(&mut self) -> Result<&[u8], ApiClientError>

Processes the response as binary data.

This method records the response in the OpenAPI specification and returns the response body as a byte slice. The response must have a binary content type.

§Returns
  • Ok(&[u8]): The response body as a byte slice
  • Err(ApiClientError): If the response is not binary
§Example
let mut client = ApiClient::builder().build()?;
let bytes = client
    .get("/api/download")?

    .await?
    .as_bytes()
    .await?;
Source

pub async fn as_raw(&mut self) -> Result<RawResult, ApiClientError>

Processes the response as raw content with complete HTTP response information.

This method records the response in the OpenAPI specification and returns a RawResult containing the HTTP status code, content type, and response body. This method supports both text and binary response content.

§Returns
  • Ok(RawResult): Complete raw response data including status, content type, and body
  • Err(ApiClientError): If processing fails
§Example
use clawspec_core::{ApiClient, RawBody};
use http::StatusCode;

let mut client = ApiClient::builder().build()?;
let raw_result = client
    .get("/api/data")?

    .await?
    .as_raw()
    .await?;

println!("Status: {}", raw_result.status_code());
if let Some(content_type) = raw_result.content_type() {
    println!("Content-Type: {}", content_type);
}

match raw_result.body() {
    RawBody::Text(text) => println!("Text body: {}", text),
    RawBody::Binary(bytes) => println!("Binary body: {} bytes", bytes.len()),
    RawBody::Empty => println!("Empty body"),
}
Source

pub async fn as_empty(&mut self) -> Result<(), ApiClientError>

Records this response as an empty response in the OpenAPI specification.

This method should be used for endpoints that return no content (e.g., DELETE operations, PUT operations that don’t return a response body).

§Example
let mut client = ApiClient::builder().build()?;

client
    .delete("/items/123")?

    .await?
    .as_empty()
    .await?;

Trait Implementations§

Source§

impl Clone for CallResult

Source§

fn clone(&self) -> CallResult

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 CallResult

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