rust_api_calling 1.0.0

A clean, idiomatic Rust HTTP client library with a single core request function and convenient GET/POST wrappers. Features builder pattern configuration, typed responses via serde generics, automatic session/cookie/XSRF management, and structured logging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;

use reqwest::header::HeaderMap;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::error::ApiError;
use crate::request::RequestConfig;
use crate::response::ApiResponse;

// ─── HTTP Method ────────────────────────────────────────────────────────────

/// Supported HTTP methods.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpMethod {
    Get,
    Post,
}

impl HttpMethod {
    fn as_reqwest(&self) -> reqwest::Method {
        match self {
            HttpMethod::Get => reqwest::Method::GET,
            HttpMethod::Post => reqwest::Method::POST,
        }
    }
}

impl std::fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HttpMethod::Get => write!(f, "GET"),
            HttpMethod::Post => write!(f, "POST"),
        }
    }
}

// ─── Session Store ──────────────────────────────────────────────────────────

/// Thread-safe session storage for XSRF tokens and cookies.
///
/// This mirrors the Swift `HelperMethods.shared.storeSessionArtifacts` pattern
/// but uses `Arc<RwLock<>>` for safe concurrent access.
#[derive(Debug, Clone, Default)]
pub struct SessionStore {
    inner: Arc<RwLock<SessionData>>,
}

#[derive(Debug, Default)]
struct SessionData {
    xsrf_token: Option<String>,
    cookie: Option<String>,
}

impl SessionStore {
    /// Create a new empty session store.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the current XSRF token, if any.
    pub fn xsrf_token(&self) -> Option<String> {
        self.inner.read().unwrap().xsrf_token.clone()
    }

    /// Get the current cookie, if any.
    pub fn cookie(&self) -> Option<String> {
        self.inner.read().unwrap().cookie.clone()
    }

    /// Update the session data from a response's headers.
    fn update_from_response(&self, headers: &HeaderMap) {
        let mut data = self.inner.write().unwrap();

        // Look for XSRF token in response headers (common header names).
        for key in &["x-xsrf-token", "xsrf-token", "x-csrf-token"] {
            if let Some(value) = headers.get(*key) {
                if let Ok(v) = value.to_str() {
                    data.xsrf_token = Some(v.to_string());
                    tracing::debug!("Updated XSRF token from header '{}'", key);
                    break;
                }
            }
        }

        // Look for Set-Cookie header.
        if let Some(value) = headers.get("set-cookie") {
            if let Ok(v) = value.to_str() {
                data.cookie = Some(v.to_string());
                tracing::debug!("Updated cookie from response");
            }
        }
    }

    /// Apply session headers to a request builder.
    fn apply_to_request(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        let data = self.inner.read().unwrap();
        let mut builder = builder;

        if let Some(ref token) = data.xsrf_token {
            builder = builder.header("X-XSRF-TOKEN", token);
        }
        if let Some(ref cookie) = data.cookie {
            builder = builder.header("Cookie", cookie);
        }

        builder
    }

    /// Manually set the XSRF token (useful for initial setup).
    pub fn set_xsrf_token(&self, token: impl Into<String>) {
        self.inner.write().unwrap().xsrf_token = Some(token.into());
    }

    /// Manually set the cookie (useful for initial setup).
    pub fn set_cookie(&self, cookie: impl Into<String>) {
        self.inner.write().unwrap().cookie = Some(cookie.into());
    }

    /// Clear all session data.
    pub fn clear(&self) {
        let mut data = self.inner.write().unwrap();
        data.xsrf_token = None;
        data.cookie = None;
    }
}

// ─── ApiClient ──────────────────────────────────────────────────────────────

/// The main HTTP client. Create it once and reuse it across your application.
///
/// Uses a builder pattern for configuration. All HTTP calls go through
/// the single `make_request` method; `get` and `post` are convenience wrappers.
///
/// # Example
/// ```no_run
/// use rust_api_calling::{ApiClient, ApiResponse};
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize)]
/// struct User {
///     id: u32,
///     name: String,
/// }
///
/// #[tokio::main]
/// async fn main() {
///     let client = ApiClient::builder()
///         .base_url("https://api.example.com")
///         .build()
///         .unwrap();
///
///     let response: ApiResponse<User> = client
///         .get("/users/1", None, None)
///         .await
///         .unwrap();
///
///     println!("User: {:?}", response.body);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ApiClient {
    /// The underlying `reqwest::Client` (connection pooled, thread-safe).
    http_client: reqwest::Client,

    /// Optional base URL prepended to all relative paths.
    base_url: Option<String>,

    /// Default headers sent with every request.
    default_headers: HashMap<String, String>,

    /// Default request timeout.
    default_timeout: Duration,

    /// Whether to manage session cookies and XSRF tokens automatically.
    session_enabled: bool,

    /// Thread-safe session store for tokens and cookies.
    pub session: SessionStore,
}

impl ApiClient {
    /// Start building a new `ApiClient` with the builder pattern.
    pub fn builder() -> ApiClientBuilder {
        ApiClientBuilder::default()
    }

    // ─── The ONE Core Function ──────────────────────────────────────────

    /// The single core function that handles ALL HTTP communication.
    ///
    /// Every other method (`get`, `post`) delegates to this function.
    /// It handles:
    /// - URL construction (base_url + path)
    /// - Query parameters (for GET)
    /// - JSON body serialization (for POST)
    /// - Default & custom headers
    /// - Session/cookie management
    /// - Bearer token authentication
    /// - Timeout configuration
    /// - Response deserialization
    /// - Structured logging
    /// - Error mapping
    ///
    /// # Type Parameter
    /// - `T`: The type to deserialize the JSON response body into.
    ///   Must implement `serde::de::DeserializeOwned`.
    /// - `B`: The type of the request body. Must implement `serde::Serialize`.
    ///
    /// # Arguments
    /// - `method` — `HttpMethod::Get` or `HttpMethod::Post`
    /// - `url` — Full URL or relative path (if `base_url` is configured)
    /// - `body` — Optional request body (serialized to JSON for POST)
    /// - `query` — Optional query parameters (appended to URL for GET)
    /// - `config` — Optional per-request configuration overrides
    pub async fn make_request<T, B>(
        &self,
        method: HttpMethod,
        url: &str,
        body: Option<&B>,
        query: Option<&[(&str, &str)]>,
        config: Option<RequestConfig>,
    ) -> Result<ApiResponse<T>, ApiError>
    where
        T: DeserializeOwned,
        B: Serialize + ?Sized,
    {
        let config = config.unwrap_or_default();

        // ── 1. Build the full URL ───────────────────────────────────────
        let full_url = self.build_url(url)?;
        tracing::info!("{} {}", method, full_url);

        // ── 2. Determine timeout ────────────────────────────────────────
        let timeout = config.timeout.unwrap_or(self.default_timeout);

        // ── 3. Create the request builder ───────────────────────────────
        let mut builder = self
            .http_client
            .request(method.as_reqwest(), &full_url)
            .timeout(timeout);

        // ── 4. Apply default headers ────────────────────────────────────
        for (key, value) in &self.default_headers {
            builder = builder.header(key.as_str(), value.as_str());
        }

        // ── 5. Apply per-request headers ────────────────────────────────
        for (key, value) in &config.headers {
            builder = builder.header(key.as_str(), value.as_str());
        }

        // ── 6. Apply bearer token ───────────────────────────────────────
        if let Some(ref token) = config.bearer_token {
            builder = builder.bearer_auth(token);
            tracing::debug!("Authorization header set");
        }

        // ── 7. Apply session cookies/XSRF ───────────────────────────────
        if self.session_enabled {
            builder = self.session.apply_to_request(builder);
        }

        // ── 8. Apply query parameters (GET) ─────────────────────────────
        if let Some(params) = query {
            builder = builder.query(params);
            tracing::debug!("Query params: {:?}", params);
        }

        // ── 9. Apply JSON body (POST) ───────────────────────────────────
        if let Some(body) = body {
            if method == HttpMethod::Post {
                let json_value = serde_json::to_value(body)?;
                tracing::debug!("Request body: {}", json_value);
                builder = builder.json(&json_value);
            }
        }

        // ── 10. Send the request ────────────────────────────────────────
        let response = builder.send().await.map_err(|e| {
            if e.is_timeout() {
                tracing::error!("Request timed out: {} {}", method, full_url);
                ApiError::Timeout
            } else {
                tracing::error!("Network error: {} {} — {}", method, full_url, e);
                ApiError::NetworkError(e)
            }
        })?;

        // ── 11. Extract response metadata ───────────────────────────────
        let status = response.status().as_u16();
        let response_headers = response.headers().clone();

        // ── 12. Update session from response headers ────────────────────
        if self.session_enabled {
            self.session.update_from_response(&response_headers);
        }

        // ── 13. Collect headers into a HashMap ──────────────────────────
        let headers: HashMap<String, String> = response_headers
            .iter()
            .filter_map(|(name, value)| {
                value
                    .to_str()
                    .ok()
                    .map(|v| (name.to_string(), v.to_string()))
            })
            .collect();

        // ── 14. Read the response body ──────────────────────────────────
        let raw_body = response.text().await.map_err(|e| {
            tracing::error!("Failed to read response body: {}", e);
            ApiError::NetworkError(e)
        })?;

        if raw_body.is_empty() {
            tracing::warn!("Empty response body from {} {}", method, full_url);
            return Err(ApiError::EmptyResponse);
        }

        tracing::debug!("Response [{}] from {}: {}", status, full_url, &raw_body);

        // ── 15. Handle non-2xx status codes ─────────────────────────────
        if !(200..300).contains(&(status as usize)) {
            tracing::error!("HTTP {} from {} {}", status, method, full_url);
            return Err(ApiError::HttpError {
                status,
                body: raw_body,
            });
        }

        // ── 16. Deserialize the response body ───────────────────────────
        let body: T = serde_json::from_str(&raw_body).map_err(|e| {
            tracing::error!(
                "Failed to deserialize response from {} {}: {}",
                method,
                full_url,
                e
            );
            ApiError::SerializationError(e)
        })?;

        Ok(ApiResponse {
            status,
            headers,
            body,
            raw_body,
        })
    }

    // ─── Convenience Wrappers ───────────────────────────────────────────

    /// Perform a GET request.
    ///
    /// This is a convenience wrapper around `make_request`.
    ///
    /// # Example
    /// ```no_run
    /// # use rust_api_calling::{ApiClient, ApiResponse};
    /// # use serde::Deserialize;
    /// # #[derive(Deserialize)] struct Post { id: u32 }
    /// # async fn example(client: &ApiClient) {
    /// // Simple GET
    /// let post: ApiResponse<Post> = client
    ///     .get("/posts/1", None, None)
    ///     .await
    ///     .unwrap();
    ///
    /// // GET with query parameters
    /// let posts: ApiResponse<Vec<Post>> = client
    ///     .get("/posts", Some(&[("userId", "1")]), None)
    ///     .await
    ///     .unwrap();
    /// # }
    /// ```
    pub async fn get<T: DeserializeOwned>(
        &self,
        url: &str,
        query: Option<&[(&str, &str)]>,
        config: Option<RequestConfig>,
    ) -> Result<ApiResponse<T>, ApiError> {
        // The empty tuple `()` is used as a placeholder for "no body".
        self.make_request::<T, ()>(HttpMethod::Get, url, None, query, config)
            .await
    }

    /// Perform a POST request with a JSON body.
    ///
    /// This is a convenience wrapper around `make_request`.
    ///
    /// # Example
    /// ```no_run
    /// # use rust_api_calling::{ApiClient, ApiResponse};
    /// # use serde::{Serialize, Deserialize};
    /// # #[derive(Serialize)] struct NewPost { title: String, body: String }
    /// # #[derive(Deserialize)] struct Post { id: u32 }
    /// # async fn example(client: &ApiClient) {
    /// let new_post = NewPost {
    ///     title: "Hello".to_string(),
    ///     body: "World".to_string(),
    /// };
    ///
    /// let created: ApiResponse<Post> = client
    ///     .post("/posts", Some(&new_post), None)
    ///     .await
    ///     .unwrap();
    /// # }
    /// ```
    pub async fn post<T, B>(
        &self,
        url: &str,
        body: Option<&B>,
        config: Option<RequestConfig>,
    ) -> Result<ApiResponse<T>, ApiError>
    where
        T: DeserializeOwned,
        B: Serialize + ?Sized,
    {
        self.make_request(HttpMethod::Post, url, body, None, config)
            .await
    }

    // ─── Internal Helpers ───────────────────────────────────────────────

    /// Construct the full URL by combining `base_url` + the given path/URL.
    ///
    /// - If `url` is already absolute (starts with "http"), use it as-is.
    /// - If `base_url` is set, prepend it to the relative path.
    /// - Otherwise, use `url` as-is.
    fn build_url(&self, url: &str) -> Result<String, ApiError> {
        let full_url = if url.starts_with("http://") || url.starts_with("https://") {
            url.to_string()
        } else if let Some(ref base) = self.base_url {
            let base = base.trim_end_matches('/');
            let path = url.trim_start_matches('/');
            format!("{}/{}", base, path)
        } else {
            url.to_string()
        };

        // Validate the URL.
        reqwest::Url::parse(&full_url)
            .map_err(|_| ApiError::InvalidUrl(full_url.clone()))?;

        Ok(full_url)
    }
}

// ─── Builder ────────────────────────────────────────────────────────────────

/// Builder for creating an `ApiClient` with custom configuration.
///
/// # Example
/// ```
/// use rust_api_calling::ApiClient;
/// use std::time::Duration;
///
/// let client = ApiClient::builder()
///     .base_url("https://api.example.com")
///     .default_timeout(Duration::from_secs(30))
///     .default_header("X-App-Version", "1.0")
///     .session_enabled(true)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Default)]
pub struct ApiClientBuilder {
    base_url: Option<String>,
    default_headers: HashMap<String, String>,
    default_timeout: Option<Duration>,
    session_enabled: bool,
}

impl ApiClientBuilder {
    /// Set the base URL that will be prepended to all relative paths.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set the default timeout for all requests (can be overridden per-request).
    pub fn default_timeout(mut self, timeout: Duration) -> Self {
        self.default_timeout = Some(timeout);
        self
    }

    /// Add a default header sent with every request.
    pub fn default_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.default_headers.insert(key.into(), value.into());
        self
    }

    /// Enable or disable automatic session/cookie management.
    ///
    /// When enabled, the client will:
    /// - Read XSRF tokens and cookies from response headers.
    /// - Automatically attach them to subsequent requests.
    pub fn session_enabled(mut self, enabled: bool) -> Self {
        self.session_enabled = enabled;
        self
    }

    /// Build the `ApiClient`.
    ///
    /// Returns an error if the underlying `reqwest::Client` cannot be created.
    pub fn build(self) -> Result<ApiClient, ApiError> {
        let http_client = reqwest::Client::builder()
            .cookie_store(self.session_enabled)
            .build()
            .map_err(ApiError::NetworkError)?;

        Ok(ApiClient {
            http_client,
            base_url: self.base_url,
            default_headers: self.default_headers,
            default_timeout: self.default_timeout.unwrap_or(Duration::from_secs(60)),
            session_enabled: self.session_enabled,
            session: SessionStore::new(),
        })
    }
}