Overview
The HTTP client abstraction provides a runtime-agnostic interface for making HTTP requests. Itβs primarily used for:- Media uploads to WhatsApp servers
- Media downloads (with streaming support)
- Fetching metadata and authentication tokens
HttpClient Trait
Methods
execute
Executes an HTTP request and buffers the entire response body.request: HttpRequest- The request to execute
HttpResponsewith buffered body on successanyhow::Erroron failure
execute_streaming
Executes an HTTP request and returns a streaming reader over the response body. Important: This is a synchronous method that must be called from withintokio::task::spawn_blocking.
request: HttpRequest- The request to execute
StreamingHttpResponsewith streaming body readeranyhow::Erroron failure or if streaming is not supported
Data Structures
HttpRequest
Represents an HTTP request with headers and optional body.Constructors
Builder Methods
HttpResponse
Represents an HTTP response with buffered body.Methods
StreamingHttpResponse
Represents an HTTP response with streaming body reader.UreqHttpClient
The default HTTP client implementation using theureq crate for synchronous HTTP requests.
Features
- Blocking I/O - Uses synchronous ureq, wrapped in
tokio::task::spawn_blocking - Streaming Support - Implements efficient streaming downloads
- Simple API - Minimal configuration required
- Thread-Safe - Implements
Clonefor easy sharing
Creating a Client
Usage Examples
Basic GET Request
POST Request with Body
Streaming Download
Internal Implementation
Theexecute method wraps ureq calls in spawn_blocking:
execute_streaming method is synchronous (no spawn_blocking) because itβs called FROM within a blocking context:
Implementing Custom HTTP Clients
You can implement custom HTTP clients for different runtimes or requirements.Example: Reqwest Client (Async)
Example: Mock Client for Testing
Usage with Client
Best Practices
- Blocking Operations - Always wrap blocking HTTP libraries in
tokio::task::spawn_blocking - Streaming for Large Files - Use
execute_streamingfor media downloads to avoid buffering - Error Handling - Return descriptive errors with context
- Timeouts - Implement request timeouts for reliability
- Retries - Consider retry logic for transient failures
- Connection Pooling - Reuse connections when possible
Media Operations
The HTTP client is primarily used for media operations in whatsapp-rust:Media Upload Flow
Media Download Flow
Testing
Unit Test Example
See Also
- Storage Traits - Storage backend abstraction
- Transport Trait - Network transport abstraction
- Client API - Main client interface
- Media Handling - Guide to sending and receiving media