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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! `pretend` HTTP client
//!
//! `pretend` is a modular, [Feign]-inspired, HTTP client based on macros. It's goal is to decouple
//! the definition of a REST API from it's implementation.
//!
//! Some features:
//! - Declarative
//! - Support Asynchronous and blocking requests
//! - HTTP client agnostic
//! - JSON support thanks to serde
//!
//! [Feign]: https://github.com/OpenFeign/feign
//!
//! # Getting started
//!
//! A REST API is described by annotating a trait:
//!
//! ```rust
//! use pretend::{pretend, Result};
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "POST", path = "/anything")]
//! async fn post_anything(&self, body: &'static str) -> Result<String>;
//! }
//! ```
//!
//! Under the hood, `pretend` will implement this trait for `Pretend`. An instance of this
//! struct can be constructed by passing a client implementation, and the REST API's base url. In
//! the following example, we are using the [`reqwest`] based client.
//!
//! [`reqwest`]: https://crates.io/crates/pretend-reqwest
//!
//! ```rust
//! use pretend::{Pretend, Url};
//! use pretend_reqwest::Client;
//! # use pretend::{pretend, Result};
//! # #[pretend]
//! # trait HttpBin {
//! # #[request(method = "POST", path = "/anything")]
//! # async fn post_anything(&self, body: &'static str) -> Result<String>;
//! # }
//!
//! # #[tokio::main]
//! # async fn main() {
//! let client = Client::default();
//! let url = Url::parse("https://httpbin.org").unwrap();
//! let pretend = Pretend::for_client(client).with_url(url);
//! let response = pretend.post_anything("hello").await.unwrap();
//! assert!(response.contains("hello"));
//! # }
//! ```
//!
//! # Sending headers, query parameters and bodies
//!
//! Headers are provided as attributes using `header`.
//!
//! ```rust
//! use pretend::{pretend, Result};
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "GET", path = "/get")]
//! #[header(name = "X-Test-Header-1", value = "abc")]
//! #[header(name = "X-Test-Header-2", value = "other")]
//! async fn get_with_headers(&self, value: i32, custom: &str) -> Result<()>;
//! }
//! ```
//!
//! Query parameters and bodies are provided as method parameters. Body type is guessed based on
//! the parameter name:
//!
//! - Parameter `body` will be sent as raw bytes.
//! - Parameter `form` will be serialized as form-encoded using `serde`.
//! - Parameter `json` will be serialized as JSON using `serde`.
//!
//! Query parameter is passed with the `query` parameter. It is also serialized using `serde`.
//!
//! ```rust
//! use pretend::{pretend, Json, Result};
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct Data {
//! value: i32,
//! }
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "POST", path = "/anything")]
//! async fn post_bytes(&self, body: Vec<u8>) -> Result<()>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn post_string(&self, body: &'static str) -> Result<()>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn post_with_query_params(&self, query: &Data) -> Result<()>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn post_json(&self, json: &Data) -> Result<()>;
//! }
//! ```
//!
//! # Handling responses
//!
//! `pretend` support a wide range of response types, based on the return type of the method.
//! The body can be returned as a `Vec<u8>`, a string or as JSON by using the [`Json`] wrapper
//! type. The unit type `()` can also be used if the body should be discarded.
//!
//! [`JsonResult`] is also offered as a convenience type. It will deserialize into a value type
//! or an error type depending on the HTTP status code.
//!
//! When retrieving body alone, an HTTP error will cause the method to return an error. It is
//! possible to prevent the method to fail and access the HTTP status code by wrapping these
//! types inside a [`Response`]. This also allows accessing response headers.
//!
//! ```rust
//! use pretend::{pretend, Json, JsonResult, Response, Result};
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Data {
//! value: i32,
//! }
//!
//! #[derive(Deserialize)]
//! struct Error {
//! error: String,
//! }
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "POST", path = "/anything")]
//! async fn get_bytes(&self) -> Result<Vec<u8>>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn get_string(&self) -> Result<String>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn get_json(&self) -> Result<Json<Data>>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn get_json_result(&self) -> Result<JsonResult<Data, Error>>;
//!
//! #[request(method = "POST", path = "/anything")]
//! async fn get_status(&self) -> Result<Response<()>>;
//! }
//! ```
//!
//! # Templating
//!
//! Request paths and headers support templating. A value between braces will be replaced by
//! a parameter with the same name. The replacement is done with `format!`, meaning that
//! any type that implement `Display` is supported.
//!
//! ```rust
//! use pretend::{pretend, Json, Pretend, Result, Url};
//! use pretend_reqwest::Client;
//! use serde::Deserialize;
//! use std::collections::HashMap;
//!
//! #[derive(Deserialize)]
//! struct Data {
//! url: String,
//! headers: HashMap<String, String>,
//! }
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "POST", path = "/{path}")]
//! #[header(name = "X-{header}", value = "{value}$")]
//! async fn get(&self, path: &str, header: &str, value: i32) -> Result<Json<Data>>;
//! }
//!
//! # #[tokio::main]
//! # async fn main() {
//! let client = Client::default();
//! let url = Url::parse("https://httpbin.org").unwrap();
//! let pretend = Pretend::for_client(client).with_url(url);
//! let response = pretend.get("anything", "My-Header", 123).await.unwrap();
//! let data = response.value();
//! assert_eq!(data.url, "https://httpbin.org/anything");
//! assert_eq!(*data.headers.get("X-My-Header").unwrap(), "123$".to_string());
//! # }
//! ```
//!
//! # URL resolvers
//!
//! `pretend` uses URL resolvers to resolve a full URL from the path in `request`. By default
//! the URL resolver will simply append the path to a base URL. More advanced resolvers can
//! be implemented with the [resolver] module.
//!
//! # Request interceptors
//!
//! `pretend` uses request interceptors to customize auto-generated requests. They can be useful
//! when dealing with authentication. They can be implemented with the [interceptor] module.
//!
//! ```rust
//! use pretend::http::header::AUTHORIZATION;
//! use pretend::http::HeaderValue;
//! use pretend::interceptor::{InterceptRequest, Request};
//! use pretend::{pretend, Error, Json, Pretend, Result, Url};
//! use pretend_reqwest::Client;
//! use serde::Deserialize;
//! use std::collections::HashMap;
//!
//! #[derive(Deserialize)]
//! struct Data {
//! url: String,
//! headers: HashMap<String, String>,
//! }
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "GET", path = "/get")]
//! async fn get(&self) -> Result<Json<Data>>;
//! }
//!
//! struct AuthInterceptor {
//! auth: String,
//! }
//!
//! impl AuthInterceptor {
//! fn new(auth: String) -> Self {
//! AuthInterceptor { auth }
//! }
//! }
//!
//! impl InterceptRequest for AuthInterceptor {
//! fn intercept(&self, mut request: Request) -> Result<Request> {
//! // Create the header, reporting failure if the header is invalid
//! let header = format!("Bearer {}", self.auth);
//! let header = HeaderValue::from_str(&header).map_err(|err| Error::Request(Box::new(err)))?;
//!
//! // Set the authorization header in the request
//! request.headers.append(AUTHORIZATION, header);
//! Ok(request)
//! }
//! }
//! # #[tokio::main]
//! # async fn main() {
//! let client = Client::default();
//! let url = Url::parse("https://httpbin.org").unwrap();
//! let auth_interceptor = AuthInterceptor::new("test".to_string());
//! let pretend = Pretend::for_client(client).with_url(url).with_request_interceptor(auth_interceptor);
//! let response = pretend.get().await.unwrap();
//! let data = response.value();
//! assert_eq!(*data.headers.get("Authorization").unwrap(), "Bearer test".to_string());
//! # }
//! ```
//!
//! # Examples
//!
//! More examples are available in the [examples folder].
//!
//! [examples folder]: https://github.com/SfietKonstantin/pretend/tree/main/pretend/examples
//!
//! # Blocking requests
//!
//! When all methods in the `pretend`-annotated trait are async, `pretend` will generate
//! an async implementation. To generate a blocking implementation, simply remove the `async`
//! keyword.
//!
//! Blocking implementations needs a blocking client implementation to be used. In the following
//! example, we are using one provided by [`reqwest`]
//!
//! ```rust
//! use pretend::{pretend, Pretend, Result, Url};
//! use pretend_reqwest::BlockingClient;
//!
//! #[pretend]
//! trait HttpBin {
//! #[request(method = "POST", path = "/anything")]
//! fn post_anything(&self, body: &'static str) -> Result<String>;
//! }
//!
//! # fn main() {
//! let client = BlockingClient::default();
//! let url = Url::parse("https://httpbin.org").unwrap();
//! let pretend = Pretend::for_client(client).with_url(url);
//! let response = pretend.post_anything("hello").unwrap();
//! assert!(response.contains("hello"));
//! # }
//! ```
//!
//! [`reqwest`]: https://crates.io/crates/pretend-reqwest
//!
//! # Non-Send implementation
//!
//! Today, Rust does not support futures in traits. `pretend` uses `async_trait` to workaround
//! that limitation. By default, `async_trait` adds the `Send` bound to futures. This implies
//! that `Pretend` itself is `Send` and `Sync`, and implies that the client implementation it uses
//! is also `Send` and `Sync`.
//!
//! However, some clients are not thread-safe, and cannot be shared between threads. To use
//! these clients with `Pretend`, you have to opt-out from the `Send` constraint on returned
//! futures by using `#[pretend(?Send)]`. This is similar to what is done in [`async_trait`].
//!
//! [`async_trait`]: https://docs.rs/async-trait/latest/async_trait/
//!
//! Clients implementations that are not thread-safe are usually called "local clients".
//!
//! # Non-Send errors
//!
//! `pretend` boxes errors returned by the client in [`Error`]. By default, it requires the error
//! to be `Send + Sync`. For some clients, especially local ones, this bound cannot be guaranteed.
//!
//! `pretend` offers the feature `local-error` as an escape latch. When enabled, this feature will
//! drop the `Send + Sync` bound on boxed errors. This feature is enabled by default for
//! `pretend-awc`, a local client that returns non-Send errors.
//!
//! # Available client implementations
//!
//! `pretend` can be used with the following HTTP clients
//!
//! - [`reqwest`](https://crates.io/crates/pretend-reqwest) (async and blocking)
//! - [`isahc`](https://crates.io/crates/pretend-isahc) (async)
//! - [`awc`](https://crates.io/crates/pretend-awc) (local async)
//! - [`ureq`](https://crates.io/crates/pretend-ureq) (blocking)
//!
//! These client implementations depends on the latest major release of each HTTP client at
//! time of the release. The `default` feature for each of the HTTP client crate is also mapped
//! to the `pretend-*` crate. To enable HTTP client features, you should add it as a dependency
//! and enable them here. If needed, you can play with the `default-features` option on the
//! `pretend-*` crate.
//!
//! The following snippet will enable `reqwest` default features
//!
//! ```toml
//! [dependencies]
//! pretend-reqwest = "0.2.2"
//! ```
//!
//! In the following snippet, no feature of `reqwest` will be enabled
//!
//! ```toml
//! [dependencies]
//! pretend-reqwest = { version = "0.2.2", default-features = false }
//! ```
//!
//! To use `reqwest` with rustls instead of the native-tls, you can do the following:
//!
//! ```toml
//! [dependencies]
//! pretend-reqwest = { version = "0.2.2", default-features = false }
//! reqwest = { version = "*", default-features = false, features = ["rustls-tls"] }
//! ```
//!
//! # Implementing a `pretend` HTTP client
//!
//! `pretend` clients wraps HTTP clients from other crates. They allow [`Pretend`] to execute
//! HTTP requests. See the [client] module level documentation for more information about
//! how to implement a client.
//!
//! # MSRV
//!
//! MSRV for the `pretend` ecosystem is Rust **1.44**.
//!
//! # The future
//!
//! Here is a quick roadmap
//!
//! - Introduce more attributes to mark method parameters (body, json, params)
pub use ;
pub use http;
pub use ;
pub use pretend;
pub use serde;
pub use url;
pub use Url;
use crate;
use crate;
use DeserializeOwned;
use ;
/// Response type
/// The pretend HTTP client
///
/// This struct is the entry point for `pretend` clients. It can be constructed with
/// an HTTP client implementation, and `pretend` annotated traits will automatically
/// be implemented by this struct.
///
/// See crate level documentation for more information
/// JSON body
///
/// This wrapper type indicates that a method should return
/// a JSON-serialized body.
/// JSON result
///
/// This wrapper type indicate that a method should return
/// JSON-serialized bodies.
///
/// When the HTTP request is successful, the `Ok` variant will
/// be returned, and when the HTTP request has failed, the
/// `Err` variant will be returned.