Expand description
HTTP client generation for OpenAPI specifications.
This module is part of the code generator that creates production-ready HTTP clients from OpenAPI specifications. It generates clients with middleware support including retry logic and request tracing.
§Overview
The client generator creates:
HttpClientstruct with middleware stack (reqwest-middleware)- Retry logic with exponential backoff (reqwest-retry)
- Request/response tracing (reqwest-tracing)
- Direct methods for all API operations (GET, POST, PUT, DELETE, PATCH)
- Comprehensive error handling with
HttpError - Builder pattern for configuration
§Generated Code Structure
For each OpenAPI specification, the generator creates:
ⓘ
// Generated client.rs file
use crate::types::*;
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use std::collections::BTreeMap;
pub struct HttpClient {
base_url: String,
api_key: Option<String>,
http_client: ClientWithMiddleware,
custom_headers: BTreeMap<String, String>,
}
impl HttpClient {
pub fn new() -> Self { /* ... */ }
pub fn with_config(retry_config: Option<RetryConfig>, enable_tracing: bool) -> Self { /* ... */ }
pub fn with_base_url(self, base_url: String) -> Self { /* ... */ }
pub fn with_api_key(self, api_key: String) -> Self { /* ... */ }
pub fn with_header(self, key: String, value: String) -> Self { /* ... */ }
// Generated operation methods
pub async fn list_items(&self) -> Result<ItemList, HttpError> { /* ... */ }
pub async fn create_item(&self, request: CreateItemRequest) -> Result<Item, HttpError> { /* ... */ }
pub async fn get_item(&self, id: impl AsRef<str>) -> Result<Item, HttpError> { /* ... */ }
}§Middleware Stack
The generated client uses reqwest-middleware to build a composable middleware stack:
-
Tracing Middleware (optional, enabled by default)
- Logs HTTP requests/responses
- Creates spans for distributed tracing
- Integrates with
tracingecosystem
-
Retry Middleware (optional, configured via TOML)
- Exponential backoff retry policy
- Automatically retries transient errors (429, 500, 502, 503, 504)
- Configurable max retries and delay bounds
§Configuration
§Via TOML
[http_client]
base_url = "https://api.example.com"
timeout_seconds = 30
[http_client.retry]
max_retries = 3
initial_delay_ms = 500
max_delay_ms = 16000
[http_client.tracing]
enabled = true§Via Rust API
use openapi_to_rust::{GeneratorConfig, http_config::*};
use std::path::PathBuf;
let config = GeneratorConfig {
spec_path: PathBuf::from("openapi.json"),
enable_async_client: true,
retry_config: Some(RetryConfig {
max_retries: 3,
initial_delay_ms: 500,
max_delay_ms: 16000,
}),
tracing_enabled: true,
// ... other fields
..Default::default()
};§Generated Client Usage
ⓘ
use crate::generated::client::HttpClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create client with retry and tracing
let client = HttpClient::new()
.with_base_url("https://api.example.com".to_string())
.with_api_key("your-api-key".to_string())
.with_header("X-Custom-Header".to_string(), "value".to_string());
// Make API calls - retries happen automatically
let items = client.list_items().await?;
println!("Found {} items", items.items.len());
Ok(())
}§HTTP Method Support
The generator supports all standard HTTP methods:
GET- List and retrieve operationsPOST- Create operationsPUT- Full update operationsPATCH- Partial update operationsDELETE- Delete operations
§Error Handling
All generated methods return Result<T, HttpError> where HttpError provides:
- Detailed error information
- Retry detection via
is_retryable() - Error categorization (client errors, server errors)
See http_error module for details.
§Implementation Details
The generator uses the following approach:
- Analyzes OpenAPI operations to extract HTTP methods, paths, parameters
- Generates typed request/response handling
- Creates method signatures with proper parameter types
- Generates path parameter substitution
- Handles query parameters and request bodies
- Configures middleware stack based on generator config