Expand description
§better-fetch
Typed HTTP client layer on top of reqwest, inspired by @better-fetch/fetch. This crate is not affiliated with the upstream TypeScript project.
§Quick flow
- Create a
Client(orClientBuilder) with a base URL. - Start a request with
Client::get/Client::post(flexibleRequestBuilder) orClient::call(typedEndpointroutes). - Configure path params, query, body, auth, retries on the builder.
- Execute with
RequestBuilder::send(bufferedResponse),RequestBuilder::send_stream(incrementalStreamingResponse),send_json, orEndpointRequestBuilder::send_json.
§Buffered vs streaming
send/send_json— full body in memory; hooks and retry predicates can read the body. WhenClientBuilder::max_response_bytesis set, the body is read via the streaming transport up to that limit (sameError::BodyTooLargeas streams).send_stream—bytes_stream()from reqwest; useStreamingResponse::collectto buffer when needed. See thestreamingmodule for limits (hooks, custom retry predicates, Tower backend).
Use .get() when you want string paths and a typed JSON response (send_json::<T>()).
Use Client::call when method, path, params, query, and response are bound to an Endpoint type.
§Cargo features
The client always uses reqwest as the default HTTP backend. Enable crate features to turn on reqwest capabilities and optional APIs.
| Feature | Description |
|---|---|
json (default) | JSON bodies, send_json, custom JsonParserFn |
rustls-tls (default) | TLS via rustls (enable native-tls instead, not both) |
native-tls | TLS via the platform stack (do not combine with rustls-tls) |
multipart | RequestBuilder::multipart |
tower | Tower transport stack via ClientBuilder::transport_stack (implies rustls-tls) |
schema | SchemaRegistry route metadata |
openapi | OpenAPI 3.0 export from schema registry |
validate | Garde validation on JSON request/response bodies |
schema-validate | Runtime JSON Schema validation (strict registry: request/response body, query, params) |
miette | DiagnosticError for labeled error reports |
otel | opentelemetry, opentelemetry_sdk, tracing_opentelemetry re-exports |
blocking, cookies | Passed through to reqwest |
sse | SSE (text/event-stream) helpers on StreamingResponse |
macros | #[derive(Endpoint)], EndpointParamsDerive, EndpointQueryDerive |
full | Common optional features bundled for internal apps |
See the repository README for full examples.
§Example (.get() — flexible path, typed response)
let client = Client::new("https://jsonplaceholder.typicode.com")?;
// send() returns Response for any status; json() fails on non-2xx
let todo: Todo = client
.get("/todos/:id")
.param("id", 1)
.send()
.await?
.json()
.await?;
// Or in one step:
let todo: Todo = client.get("/todos/:id").param("id", 1).send_json().await?;§Example (typed endpoint — method, path, params, response)
define_params!(GetTodoParams for "/todos/:id" { id: u64 });
struct GetTodo;
impl Endpoint for GetTodo {
const METHOD: Method = Method::GET;
const PATH: &'static str = "/todos/:id";
type Response = Todo;
type Params = GetTodoParams;
type Query = ();
type Body = ();
type Headers = ();
}
let client = Client::new("https://jsonplaceholder.typicode.com")?;
let todo = client
.call::<GetTodo>()
.params(GetTodoParams { id: 1 })
.send_json()
.await?;Re-exports§
pub use api_response::into_api_result;jsonpub use api_response::ApiResponseExt;jsonpub use auth::AsyncTokenProvider;pub use auth::Auth;pub use auth::TokenSource;pub use backend::HttpBackend;pub use backend::HttpBody;pub use backend::HttpRequest;pub use backend::HttpResponse;pub use backend::HttpStreamingResponse;pub use backend::RecordedBodyKind;pub use backend::RecordedRequest;pub use backend::RecordingBackend;pub use backend::ReqwestBackend;pub use client::Client;pub use client::ClientBuilder;pub use client::ClientConfig;pub use endpoint::DefaultParamsInitial;pub use endpoint::Endpoint;pub use endpoint::EndpointBody;pub use endpoint::EndpointHeaders;pub use endpoint::EndpointParams;pub use endpoint::EndpointParamsInitial;pub use endpoint::EndpointQuery;pub use endpoint::EndpointRequestBuilder;pub use endpoint::NeedsBody;pub use endpoint::NeedsParams;pub use endpoint::ParamsBuilderState;pub use endpoint::Ready;pub use error::Error;pub use error::TransportKind;pub use hooks::ErrorContext;pub use hooks::Hooks;pub use hooks::RequestContext;pub use hooks::ResponseContext;pub use hooks::StreamingResponseContext;pub use hooks::StreamingResponseMeta;pub use hooks::StreamingSuccessContext;pub use hooks::SuccessContext;pub use plugin::Plugin;pub use plugin::PluginRegistry;pub use plugin::PreparedRequest;pub use plugins::LoggerPlugin;pub use request::RequestBuilder;pub use response::Response;pub use response::ResponseBodyKind;pub use retry::default_should_retry;pub use retry::parse_retry_after;pub use retry::RetryPolicy;pub use retry::ShouldRetryFn;pub use schema::EndpointSchema;schemapub use schema::SchemaRegistry;schemapub use sse::parse_sse_events;ssepub use sse::SseDecoder;ssepub use sse::SseEvent;ssepub use sse::SseEventStream;ssepub use streaming::BodyStream;pub use streaming::StreamingResponse;pub use openapi::OpenApiBuilder;openapipub use openapi::OpenApiComponents;openapipub use openapi::OpenApiDocument;openapipub use openapi::OpenApiInfo;openapipub use openapi::OpenApiOperation;openapipub use openapi::OpenApiSchemaRef;openapipub use openapi::OpenApiServer;openapipub use tower::BoxHttpService;towerpub use tower::BoxStreamingHttpService;towerpub use tower::ReqwestHttpService;towerpub use tower::ReqwestStreamingHttpService;towerpub use tower::ServiceBackend;towerpub use miette_diagnostic::DiagnosticError;miettepub use otel::opentelemetry;otelpub use otel::opentelemetry_sdk;otelpub use otel::tracing_opentelemetry;otel
Modules§
- api_
response - Helpers for typed success vs error response bodies.
- auth
- Authentication for clients and individual requests.
- backend
- HTTP transport abstraction.
- cancel
- Request cancellation (
CancellationToken) compatible with cooperative async abort. - client
- HTTP client, builder, and shared configuration.
- endpoint
- Typed API routes via the
Endpointtrait. - error
- Error types and helpers for HTTP, transport, hooks, and retries.
- hooks
- Lifecycle hooks for requests and responses.
- miette_
diagnostic miette - Rich diagnostics for
Errorwhen themiettefeature is enabled. - multipart
multipart - Re-export of reqwest multipart types (feature
multipart). multipart/form-data - openapi
openapi - OpenAPI 3.0 document builder (requires
openapifeature). - otel
otel - OpenTelemetry re-exports when the
otelfeature is enabled. - plugin
- Plugin hooks run after URL construction and auth, before request lifecycle hooks.
- plugins
- Built-in plugins.
- prelude
- Convenient re-exports for application code.
- request
- Per-request fluent builder.
- response
- HTTP response wrapper with a fully buffered body.
- retry
- Retry policies for transport and HTTP failures.
- schema
schema - Schema registry for endpoint metadata (requires
schemafeature). - schema_
validate schema-validate - Runtime JSON Schema validation against a
SchemaRegistry. - sse
sse - Server-Sent Events (
text/event-stream) helpers forStreamingResponse. - streaming
- Streaming HTTP responses (
send_stream). - tower
tower - Tower transport integration (
towerfeature).
Macros§
- define_
params - Defines path parameters for a route and implements
EndpointParams. - endpoint
- Defines a simple
Endpointwith optional typed params and query. - impl_
serde_ endpoint_ query json - Implements
EndpointQueryfor a serde-serializable query struct (featurejson).
Structs§
- Cancellation
Token - A token which can be used to signal a cancellation request to one or more tasks.
Enums§
- Query
Value - Query parameter value (scalar or repeated).
Functions§
- json_
parser json - Wraps a custom JSON parse function for use with
ClientBuilder::json_parser. - path_
param_ names - Returns
:paramsegment names in left-to-right path order (ignores an embedded?query). - serde_
json_ parser json - Default parser using
serde_json::from_slice(same semantics as the fast path, as aJsonParserFn).
Type Aliases§
- Json
Parser Fn json - Parses response bytes into
serde_json::Valuebefore deserializing toT. - Result
- Result alias using
Error.
Derive Macros§
- Endpoint
Derive macros - Derives
Endpoint. - Endpoint
Params Derive macros - Derives
EndpointParamsfor a struct with one field per:paramsegment in#[endpoint(path = "...")]. - Endpoint
Query Derive macros - Derives
EndpointQueryfor a serde-serializable query struct.