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
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2025 Michael Dippery <michael@monkey-robot.com>
//! Traits and structs for communicating with HTTP servers.
//!
//! In this context, a "service" is a mechanism for communicating with a
//! remote HTTP server; for example, it provides a uniform interface for
//! making GET and POST requests and receiving an HTTP response. It might
//! be more reasonable to think of this as an HTTP _client_, but here,
//! we refer to "service" because it is a proxy for a remote HTTP service,
//! and we want to avoid confusion with an _API client_, which will most
//! likely use this "service".
//!
//! HTTP service structs are often created to provide low-level HTTP
//! communication for API clients.
//!
//! # Usage
//!
//! If HTTP service structs are most commonly used by API clients, why use
//! a separate HTTP service struct at all? Could an API client not just,
//! e.g., create its own Reqwest client and call its methods directly?
//!
//! An API client certainly could do so, but that presents problems for
//! testing. It is often useful to provide static responses when testing
//! code that communicates over HTTP, and it is especially useful in unit
//! tests to avoid making external HTTP calls. Thus, it is often useful for
//! API clients to take a generic HTTP service as an argument; a test
//! client that returns static responses can be implemented and passed to
//! the API client during testing.
//!
//! To simplify the API clients' interfaces, a default constructor can
//! create a "real" HTTP service, and a private method that is only
//! available for internal tests can take an HTTP service instance.
//!
//! ```
//! use hypertyper::prelude::*;
//! use hypertyper::auth::Auth;
//! use reqwest::{header, StatusCode};
//! use serde::{Serialize, de::DeserializeOwned};
//! use std::fs;
//!
//! pub struct RealService {
//! auth: Auth,
//! client: HttpClient,
//! }
//!
//! impl RealService {
//! pub fn new(auth: Auth, factory: HttpClientFactory) -> Self {
//! let client = factory.create();
//! Self { auth, client }
//! }
//! }
//!
//! impl HttpGet for RealService {
//! async fn get<U>(&self, uri: U) -> HttpResult<String>
//! where
//! U: IntoUrl + Send
//! {
//! Ok(self.client.get(uri).send().await?.text().await?)
//! }
//! }
//!
//! impl HttpPost for RealService {
//! async fn post<U, D, R>(&self, uri: U, auth: &Auth, data: &D) -> HttpResult<R>
//! where
//! U: IntoUrl + Send,
//! D: Serialize + Sync,
//! R: DeserializeOwned,
//! {
//! let json_object = self
//! .client
//! .post(uri)
//! .header(header::CONTENT_TYPE, "application/json")
//! .json(data)
//! .send()
//! .await?
//! .json::<R>()
//! .await?;
//! Ok(json_object)
//! }
//! }
//!
//! #[derive(Default)]
//! pub struct TestService;
//!
//! impl HttpGet for TestService {
//! async fn get<U>(&self, uri: U) -> HttpResult<String>
//! where
//! U: IntoUrl + Send
//! {
//! let path = format!("tests/data{}", uri.as_str());
//! Ok(fs::read_to_string(path).expect("could not find test data"))
//! }
//! }
//!
//! impl HttpPost for TestService {
//! async fn post<U, D, R>(&self, uri: U, auth: &Auth, data: &D) -> HttpResult<R>
//! where
//! U: IntoUrl + Send,
//! D: Serialize + Sync,
//! R: DeserializeOwned,
//! {
//! Err(HttpError::Http(StatusCode::INTERNAL_SERVER_ERROR))
//! }
//! }
//!
//! pub struct ApiClient<S: HttpService> {
//! service: S,
//! }
//!
//! impl<S: HttpService> ApiClient<S> {
//! // Note: Not pub! This will only be available in tests within the module.
//! // Use pub(crate) fn if with_service() should be available in test utils
//! // modules, too.
//! fn with_service(service: S) -> Self {
//! Self { service }
//! }
//! }
//!
//! impl ApiClient<RealService> {
//! pub fn new(auth: Auth) -> Self {
//! let factory = HttpClientFactory::with_user_agent("my cool user agent");
//! let service = RealService::new(auth, factory);
//! Self::with_service(service)
//! }
//! }
//!
//! let auth = Auth::new("some-cool-api-key");
//! let real_client = ApiClient::new(auth);
//!
//! // APIClient::with_service() is only available within the module,
//! // which simplifies the public API while allowing easy testing.
//! let test_client = ApiClient::with_service(TestService::default());
//! ```
//!
//! Together, an HTTP service trait and its various concrete implementations
//! provide a uniform way of communicating over HTTP, whether code is
//! under test or live in production.
use crate*;
use Serialize;
use DeserializeOwned;
/// An [HTTP service](HttpService) that only makes HTTP GET requests.
/// An [HTTP service](HttpService) that only makes HTTP POST requests.
/// A service for making calls to an HTTP server and handling responses.
///
/// # Usage
///
/// Using this trait, clients can implement different ways of connecting
/// to an HTTP server, such as an actual connector for production code,
/// and a mocked connector for testing purposes.
///
/// See the [module documentation] for examples on how to use this trait
/// in both testing and production contexts.
///
/// [module documentation]: crate::service
///
/// # Implementing
///
/// This trait is automatically adopted by any types that implement both
/// [`HttpGet`] and [`HttpPost`], so you can define a trait like this:
///
/// ```
/// use hypertyper::prelude::*;
/// use reqwest::StatusCode;
/// use serde::Serialize;
/// use serde::de::DeserializeOwned;
/// use std::fmt::Debug;
///
/// #[derive(Debug)]
/// pub struct MyHTTPService;
///
/// impl HttpGet for MyHTTPService {
/// async fn get<U>(&self, uri: U) -> HttpResult<String>
/// where
/// U: IntoUrl + Send,
/// {
/// println!("Hello, GET! {:?}", uri.into_url());
/// Ok(String::from("Hello, GET!"))
/// }
/// }
///
/// impl HttpPost for MyHTTPService {
/// async fn post<U, D, R>(&self, uri: U, auth: &Auth, _data: &D) -> HttpResult<R>
/// where
/// U: IntoUrl + Send,
/// D: Serialize + Sync,
/// R: DeserializeOwned,
/// {
/// print!("Hello, POST! {:?} {:?}", uri.into_url(), auth);
/// Err(HttpError::Http(StatusCode::INTERNAL_SERVER_ERROR))
/// }
/// }
///
/// pub fn hello_service(service: impl HttpService + Debug) {
/// println!("Hello, service! {:?}", service);
/// }
/// ```
///
/// Note that `HTTPService` is automatically implemented. Pretty cool, huh?