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:
- Empty responses (204 No Content, etc.):
as_empty() - JSON responses:
as_json::<T>() - Optional JSON responses (204/404 → None):
as_optional_json::<T>() - Type-safe error handling:
as_result_json::<T, E>()(2xx → Ok(T), 4xx/5xx → Err(E)) - Optional with errors:
as_result_option_json::<T, E>()(combines optional and error handling) - Text responses:
as_text() - Binary responses:
as_bytes() - Raw response access:
as_raw()(includes status code, content-type, and body)
§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
impl CallResult
Sourcepub async fn as_json_redacted<T>(
&mut self,
) -> Result<RedactionBuilder<T>, ApiClientError>where
T: DeserializeOwned + ToSchema + 'static,
Available on crate feature redaction only.
pub async fn as_json_redacted<T>(
&mut self,
) -> Result<RedactionBuilder<T>, ApiClientError>where
T: DeserializeOwned + ToSchema + 'static,
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
T- The type to deserialize into. Must implementDeserializeOwned,ToSchema, and have a'staticlifetime.
§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
impl CallResult
Sourcepub async fn as_json<T>(&mut self) -> Result<T, ApiClientError>where
T: DeserializeOwned + ToSchema + 'static,
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 implementDeserializeOwned,ToSchema, and'static
§Returns
Ok(T): The deserialized response objectErr(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?;Sourcepub async fn as_optional_json<T>(&mut self) -> Result<Option<T>, ApiClientError>where
T: DeserializeOwned + ToSchema + 'static,
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 implementDeserializeOwned,ToSchema, and'static
§Returns
Ok(None): If the status code is 204 or 404Ok(Some(T)): The deserialized response object for other successful responsesErr(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());Sourcepub async fn as_result_json<T, E>(
&mut self,
) -> Result<Result<T, E>, ApiClientError>
pub async fn as_result_json<T, E>( &mut self, ) -> Result<Result<T, E>, ApiClientError>
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 implementDeserializeOwned,ToSchema, and'staticE: The error response type, must implementDeserializeOwned,ToSchema, and'static
§Returns
Ok(T): The deserialized success response for 2xx status codesErr(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),
}Sourcepub async fn as_result_option_json<T, E>(
&mut self,
) -> Result<Result<Option<T>, E>, ApiClientError>
pub async fn as_result_option_json<T, E>( &mut self, ) -> Result<Result<Option<T>, E>, ApiClientError>
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 implementDeserializeOwned,ToSchema, and'staticE: The error response type, must implementDeserializeOwned,ToSchema, and'static
§Returns
Ok(None): For 204 (No Content) or 404 (Not Found) status codesOk(Some(T)): The deserialized success response for other 2xx status codesErr(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),
}Sourcepub async fn as_text(&mut self) -> Result<&str, ApiClientError>
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 sliceErr(ApiClientError): If the response is not text
§Example
let mut client = ApiClient::builder().build()?;
let text = client
.get("/api/status")?
.await?
.as_text()
.await?;Sourcepub async fn as_bytes(&mut self) -> Result<&[u8], ApiClientError>
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 sliceErr(ApiClientError): If the response is not binary
§Example
let mut client = ApiClient::builder().build()?;
let bytes = client
.get("/api/download")?
.await?
.as_bytes()
.await?;Sourcepub async fn as_raw(&mut self) -> Result<RawResult, ApiClientError>
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 bodyErr(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"),
}Sourcepub async fn as_empty(&mut self) -> Result<(), ApiClientError>
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
impl Clone for CallResult
Source§fn clone(&self) -> CallResult
fn clone(&self) -> CallResult
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more