hapic 0.3.0

HTTP API Client (hapic): A Rust crate for quickly creating nice-to-use client libraries for HTTP APIs, in particular, there's lots of tooling around HTTP JSON APIs.
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
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
//! A Rust crate for quickly creating nice-to-use client libraries for HTTP APIs, in particular,
//! there's lots of tooling around HTTP JSON APIs.
//!
//! **This is still a work in progress.**
//!
//! ## Example: defining a JSON API client
//!
//! ### Super Simple
//!
//! We'll start with a simple dummy API, it has the following endpoints:
//!
//! ```text
//! >> POST /add
//! >> { "a": 2, "b": 3 }
//! << { "c": 5 }
//!
//! >> POST /sub
//! >> { "a": 6, "b": 3 }
//! << { "c": 3 }
//!
//! >> POST /factorial
//! >> { "a": 4 }
//! << { "c": 24 }
//! ```
//!
//! We can define a client for this API as such:
//!
//! ```
//! use hapic::json_api;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize)]
//! struct Add {
//!     a: u32,
//!     b: u32,
//! }
//!
//! #[derive(Serialize)]
//! struct Sub {
//!     a: u32,
//!     b: u32,
//! }
//!
//! #[derive(Serialize)]
//! struct Factorial {
//!     a: u8,
//! }
//!
//! #[derive(Deserialize, PartialEq, Eq, Debug)]
//! struct Output {
//!     c: u64,
//! }
//!
//! json_api!(
//!     struct TestClient<B, T: Transport<B>>;
//!     trait TestApiCall;
//!
//!     simple {
//!         "/add": Add => Output;
//!         "/sub": Sub => Output;
//!         "/factorial": Factorial => Output;
//!     }
//! );
//! ```
//!
//! Now, the call types (`Add`, `Sub` and `Factorial`) all implement `TestApiCall`.
//!
//! We can make an API call (to `http://localhost:8080`) using:
//!
//! ```
//! # use hapic::json_api;
//! # use serde::{Deserialize, Serialize};
//! #
//! # #[derive(Serialize)]
//! # struct Add {
//! #     a: u32,
//! #     b: u32,
//! # }
//! #
//! # #[derive(Serialize)]
//! # struct Sub {
//! #     a: u32,
//! #     b: u32,
//! # }
//! #
//! # #[derive(Serialize)]
//! # struct Factorial {
//! #     a: u8,
//! # }
//! #
//! # #[derive(Deserialize, PartialEq, Eq, Debug)]
//! # struct Output {
//! #     c: u64,
//! # }
//! #
//! # json_api!(
//! #     struct TestClient<B, T: Transport<B>>;
//! #     trait TestApiCall;
//! #
//! #     simple {
//! #         "/add": Add => Output;
//! #         "/sub": Sub => Output;
//! #         "/factorial": Factorial => Output;
//! #     }
//! # );
//! # async fn example() {
//! let client = TestClient::new("http://localhost:8000".into());
//! let output = client.call(Add { a: 1, b: 2 }).await.unwrap();
//! assert_eq!(output, Output { c: 3 });
//! # }
//! ```
//!
//! ### With Conversions
//!
//! Now suppose we have a single endpoint for all these operations:
//!
//! ```text
//! >> POST /op
//! >> { "a": 2, "b": 3, "operation": "add" }
//! << { "c": 5 }
//!
//! >> POST /op
//! >> { "a": 6, "b": 3, "operation": "sub" }
//! << { "c": 3 }
//!
//! >> POST /op
//! >> { "a": 4, "operation": "factorial" }
//! << { "c": 24 }
//! ```
//!
//! We *could* define the type:
//!
//! ```
//! #[derive(serde::Serialize)]
//! struct Operation {
//!     operation: &'static str,
//!     a: u32,
//!     #[serde(skip_serializing_if = "Option::is_none")]
//!     b: Option<u32>,
//! }
//! ```
//!
//! This this isn't very idiomatic! Firstly, the user can put any string as the operation, but we
//! know our API server only accepts `add`, `sub` or `factorial`. In addition, if `b` is `Some` in a
//! factorial operation, or is `None` in `add` or `sub`, we'll have an invalid call.
//!
//! We want to make this safe, so we can define two types, one for the API call, and another which
//! will be sent as the JSON body.
//!
//! ```rust
//! # use hapic::json_api;
//! #
//! # #[derive(serde::Deserialize, PartialEq, Eq, Debug)]
//! # struct Output {
//! #     c: u64,
//! # }
//! enum Operation {
//!     Add((u32, u32)),
//!     Sub((u32, u32)),
//!     Factorial(u8),
//! }
//!
//! #[derive(serde::Serialize)]
//! struct JsonOperation {
//!     operation: &'static str,
//!     a: u32,
//!     #[serde(skip_serializing_if = "Option::is_none")]
//!     b: Option<u32>,
//! }
//!
//! impl From<Operation> for JsonOperation {
//!     fn from(op: Operation) -> JsonOperation {
//!         match op {
//!             Operation::Add((a, b)) => JsonOperation {
//!                 operation: "add",
//!                 a,
//!                 b: Some(b),
//!             },
//!             Operation::Sub((a, b)) => JsonOperation {
//!                 operation: "sub",
//!                 a,
//!                 b: Some(b),
//!             },
//!             Operation::Factorial(x) => JsonOperation {
//!                 operation: "factorial",
//!                 a: x as u32,
//!                 b: None,
//!             },
//!         }
//!     }
//! }
//!
//! json_api!(
//!     struct TestClient<B, T: Transport<B>>;
//!     trait TestApiCall;
//!
//!     json {
//!         "/op": Operation as JsonOperation => Output as Output;
//!     }
//! );
//! ```
//!
//! Of course, we could have achieved the same thing using a custom serialization implementation,
//! but in many cases (especially for deserializing the output) it's significantly faster to define
//! two types and implement `TryInto` or `Into` between them.
//!
//! Finally, we make another tweak. Out `Output` type is just a single number, so why not return a
//! number as the result.
//!
//! ```rust
//! # enum Operation {
//! #     Add((u32, u32)),
//! #     Sub((u32, u32)),
//! #     Factorial(u8),
//! # }
//! #
//! # #[derive(serde::Serialize)]
//! # struct JsonOperation {
//! #     operation: &'static str,
//! #     a: u32,
//! #     #[serde(skip_serializing_if = "Option::is_none")]
//! #     b: Option<u32>,
//! # }
//! #
//! # impl From<Operation> for JsonOperation {
//! #     fn from(op: Operation) -> JsonOperation {
//! #         match op {
//! #             Operation::Add((a, b)) => JsonOperation {
//! #                 operation: "add",
//! #                 a,
//! #                 b: Some(b),
//! #             },
//! #             Operation::Sub((a, b)) => JsonOperation {
//! #                 operation: "sub",
//! #                 a,
//! #                 b: Some(b),
//! #             },
//! #             Operation::Factorial(x) => JsonOperation {
//! #                 operation: "factorial",
//! #                 a: x as u32,
//! #                 b: None,
//! #             },
//! #         }
//! #     }
//! # }
//! # #[derive(serde::Deserialize, PartialEq, Eq, Debug)]
//! # struct Output {
//! #     c: u64,
//! # }
//! #
//! # use hapic::json_api;
//! impl From<Output> for u64 {
//!     fn from(output: Output) -> u64 {
//!         output.c
//!     }
//! }
//!
//! json_api!(
//!     struct TestClient<B, T: Transport<B>>;
//!     trait TestApiCall;
//!
//!     json {
//!         "/op": Operation as JsonOperation => Output as u64;
//!     }
//! );
//! ```
//!
//! Now we can make API calls really neatly:
//!
//! ```rust
//! # enum Operation {
//! #     Add((u32, u32)),
//! #     Sub((u32, u32)),
//! #     Factorial(u8),
//! # }
//! #
//! # #[derive(serde::Serialize)]
//! # struct JsonOperation {
//! #     operation: &'static str,
//! #     a: u32,
//! #     #[serde(skip_serializing_if = "Option::is_none")]
//! #     b: Option<u32>,
//! # }
//! #
//! # impl From<Operation> for JsonOperation {
//! #     fn from(op: Operation) -> JsonOperation {
//! #         match op {
//! #             Operation::Add((a, b)) => JsonOperation {
//! #                 operation: "add",
//! #                 a,
//! #                 b: Some(b),
//! #             },
//! #             Operation::Sub((a, b)) => JsonOperation {
//! #                 operation: "sub",
//! #                 a,
//! #                 b: Some(b),
//! #             },
//! #             Operation::Factorial(x) => JsonOperation {
//! #                 operation: "factorial",
//! #                 a: x as u32,
//! #                 b: None,
//! #             },
//! #         }
//! #     }
//! # }
//! #
//! # #[derive(serde::Deserialize, PartialEq, Eq, Debug)]
//! # struct Output {
//! #     c: u64,
//! # }
//! #
//! # use hapic::json_api;
//! #
//! # impl From<Output> for u64 {
//! #     fn from(output: Output) -> u64 {
//! #         output.c
//! #     }
//! # }
//! #
//! # json_api!(
//! #     struct TestClient<B, T: Transport<B>>;
//! #     trait TestApiCall;
//! #
//! #     json {
//! #         "/op": Operation as JsonOperation => Output as u64;
//! #     }
//! # );
//! # async fn example() {
//! let client = TestClient::new(std::borrow::Cow::Borrowed("http://localhost:8000"));
//! let output = client.call(Operation::Add((1, 2))).await.unwrap();
//! assert_eq!(output, 3);
//! # }
//! ```
//!
//! ## Real-World Example
//!
//! For a real world example, see `cloudconvert-rs`.
//!
//! ## Using the macros
//!
//! In the simple examples above, we made use of the `json_api!` macro to generate the client and
//! API calls.
//!
//! The `json_api!` macro is just a shorthand way of using the `client!` macro, then the
//! `json_api_call!` macro, both of which have detailed documentation.
//!
//! ## Implementing Traits Directly
//!
//! You can also (and in some cases will want to) implement the traits directly. Here's a summary,
//! from most abstract to least abstract:
//!
//! - [`SimpleApiCall`]: a JSON API call where the input and output types undergo no conversion
//!   (automatically implements [`JsonApiCall`]).
//! - [`JsonApiCall`]: a JSON api call, allowing for conversion of the request and response
//!   (automatically implements [`ApiCall`]).
//! - [`ApiCall`]: a generic API call (automatically implements [`RawApiCall`]).
//! - [`RawApiCall`]: the lowest level trait for API calls, you probably want to implement one of
//!   the others.

use std::borrow::Cow;
use std::marker::PhantomData;

pub use http;
pub use serde_json;

#[cfg(feature = "hyper")]
pub use hyper;
#[cfg(feature = "hyper")]
pub use hyper_tls;

use http::{
    header::{self, HeaderMap, HeaderValue},
    Method, StatusCode,
};
use serde::{Deserialize, Serialize};

pub mod transport;

#[cfg(feature = "hyper")]
/// Macro for generating the client and ApiCall type.
///
/// If you're defining JSON API calls at the same time, you can use [`json_api`] instead.
///
/// For example:
/// ```
/// hapic::client!(
///     pub struct Client<B, T: Transport<B>>;
///     pub trait ApiCall;
/// );
/// ```
///
/// Creates:
/// ```
/// use hapic::RawApiCall;
/// use hapic::transport::Transport;
///
/// pub struct Client<B, T: Transport<B>> {
///     pub client: hapic::Client<B, T>
/// }
///
/// pub trait ApiCall: RawApiCall {}
/// ```
///
/// The `Client` type has, by default, two impls:
///
/// ```
/// use hapic::{Error, RawApiCall};
/// use hapic::transport::HttpsTransport;
///
/// # use hapic::transport::Transport;
/// # pub struct Client<B, T: Transport<B>> {
/// #     pub client: hapic::Client<B, T>
/// # }
///
/// pub trait ApiCall: RawApiCall {}
///
/// impl Client<hyper::Body, HttpsTransport> {
///     /// Create a new client to the provided endpoint, using `hyper` and `HttpsTransport`.
///     pub fn new(endpoint: std::borrow::Cow<'static, str>) -> Self {
///         Client {
///             client: hapic::Client::new_https_client(endpoint),
///         }
///     }
/// }
///
/// impl<B: Send + Sync, T: Transport<B>> Client<B, T> {
///     pub async fn call<C>(
///         &self,
///         api_call: C,
///     ) -> std::result::Result<C::Output, Error>
///     where
///         C: ApiCall + Send,
///         B: From<<C as RawApiCall>::RequestBody>,
///     {
///         RawApiCall::request(api_call, &self.client).await
///     }
/// }
/// ```
#[macro_export]
macro_rules! client {
    (
        $(#[$client_meta:meta])*
        $client_vis:vis struct $Client:ident<B, T: $($(hapic::)?transport::)?Transport<B>>;
        $(#[$trait_meta:meta])*
        $trait_vis:vis trait $ApiCall:ident;
    ) => {
        $(#[$client_meta])*
        $client_vis struct $Client<B, T: $crate::transport::Transport<B>> {
            pub client: $crate::Client<B, T>,
        }

        $(#[$trait_meta])*
        $trait_vis trait $ApiCall: $crate::RawApiCall {}

        impl $Client<$crate::hyper::Body, $crate::transport::HttpsTransport> {
            /// Create a new client to the provided endpoint, using `hyper` and `HttpsTransport`.
            pub fn new(endpoint: std::borrow::Cow<'static, str>) -> Self {
                $Client {
                    client: $crate::Client::new_https_client(endpoint),
                }
            }
        }

        impl<B: Send + Sync, T: $crate::transport::Transport<B>> $Client<B, T> {
            /// Make an API call.
            pub async fn call<C>(
                &self,
                api_call: C,
            ) -> std::result::Result<<C as $crate::RawApiCall>::Output, $crate::Error>
            where
                C: $ApiCall + Send,
                B: From<<C as $crate::RawApiCall>::RequestBody>,
            {
                $crate::RawApiCall::request(api_call, &self.client).await
            }
        }
    };
}

#[cfg(not(feature = "hyper"))]
/// Macro for generating the client and ApiCall type.
///
/// If you're defining JSON API calls at the same time, you can use [`json_api`] instead.
///
/// For example:
/// ```
/// hapic::client!(
///     pub struct Client<B, T: Transport<B>>;
///     pub trait ApiCall;
/// );
/// ```
///
/// Creates:
/// ```
/// use hapic::RawApiCall;
/// use hapic::transport::Transport;
///
/// pub struct Client<B, T: Transport<B>> {
///     pub client: hapic::Client<B, T>
/// }
///
/// pub trait ApiCall: RawApiCall {}
/// ```
///
/// The `Client` type has, by default, two impls:
///
/// ```
/// use hapic::{Error, RawApiCall};
/// use hapic::transport::HttpsTransport;
///
/// # use hapic::transport::Transport;
/// # pub struct Client<B, T: Transport<B>> {
/// #     pub client: hapic::Client<B, T>
/// # }
///
/// pub trait ApiCall: RawApiCall {}
///
/// impl Client<hyper::Body, HttpsTransport> {
///     /// Create a new client to the provided endpoint, using `hyper` and `HttpsTransport`.
///     pub fn new(endpoint: std::borrow::Cow<'static, str>) -> Self {
///         Client {
///             client: hapic::Client::new_https_client(endpoint),
///         }
///     }
/// }
///
/// impl<B: Send + Sync, T: Transport<B>> Client<B, T> {
///     pub async fn call<C>(
///         &self,
///         api_call: C,
///     ) -> std::result::Result<C::Output, Error>
///     where
///         C: ApiCall + Send,
///         B: From<<C as RawApiCall>::RequestBody>,
///     {
///         RawApiCall::request(api_call, &self.client).await
///     }
/// }
/// ```
#[macro_export]
macro_rules! client {
    (
        $(#[$client_meta:meta])*
        $client_vis:vis struct $Client:ident<B, T: $($(hapic::)?transport::)?Transport<B>>;
        $(#[$trait_meta:meta])*
        $trait_vis:vis trait $ApiCall:ident;
    ) => {
        $(#[$client_meta])*
        $client_vis struct $Client<B, T: $crate::transport::Transport<B>> {
            pub client: $crate::Client<B, T>,
        }

        $(#[$trait_meta])*
        $trait_vis trait $ApiCall: $crate::RawApiCall {}

        impl<B: Send + Sync, T: $crate::transport::Transport<B>> $Client<B, T> {
            /// Make an API call.
            pub async fn call<C>(
                &self,
                api_call: C,
            ) -> std::result::Result<<C as $crate::RawApiCall>::Output, $crate::Error>
            where
                C: $ApiCall + Send,
                B: From<<C as $crate::RawApiCall>::RequestBody>,
            {
                $crate::RawApiCall::request(api_call, &self.client).await
            }
        }
    };
}

/// Define a JSON api client and some API calls.
///
/// This is shorthand for the [`client`] macro, followed by the [`json_api_call`] macro.
///
/// See the crate level documentation for examples, and the constituent macros for more detailed
/// documentation.
#[macro_export]
macro_rules! json_api {
    (
        $(#[$client_meta:meta])*
        $client_vis:vis struct $Client:ident<B, T: $($(hapic::)?transport::)?Transport<B>>;
        $(#[$trait_meta:meta])*
        $trait_vis:vis trait $ApiCall:ident;
        $($tt:tt)*
    ) => {
        $crate::client!(
            $(#[$client_meta])*
            $client_vis struct $Client<B, T: Transport<B>>;
            $(#[$trait_meta])*
            $trait_vis trait $ApiCall;
        );
        $crate::json_api_call!(
            ApiCall: $ApiCall;
            $($tt)*
        );
    }
}

/// A macro for quickly implementing the various JSON API call traits.
///
/// # SimpleApiCall
///
/// To implement [`SimpleApiCall`], use:
///
/// ```
/// # use hapic::json_api_call;
/// # #[derive(serde::Serialize)]
/// # struct Foo;
/// # #[derive(serde::Deserialize)]
/// # struct Bar;
///
/// json_api_call!(simple "/foo": Foo => Bar);
/// ```
///
/// This implements [``SimpleApiCall`] for `Foo`, with output type `Bar`. The API call formats the
/// value (of type `Foo`) to a JSON string, makes a post request to `"/foo"` and then parses the
/// results as type `Bar` (expecting a 200-299 response).
///
/// `Foo` must implement [`serde::Serialize`] and `Bar` must implement [`serde::Deserialize`].
///
/// To customise the request method used, you can write:
///
/// ```
/// # use hapic::json_api_call;
/// # #[derive(serde::Serialize)]
/// # struct Foo;
/// # #[derive(serde::Deserialize)]
/// # struct Bar;
///
/// json_api_call!(simple PUT "/foo": Foo => Bar);
/// ```
///
/// Replacing `PUT` with any HTTP method.
///
/// # JsonApiCall
///
/// If you require type conversion of the input and/or output type, you can instead implement
/// [`JsonApiCall`] with:
///
/// ```
/// # use hapic::json_api_call;
/// # struct Foo;
/// # #[derive(serde::Serialize)]
/// # struct FooJson;
/// # #[derive(serde::Deserialize)]
/// # struct BarJson;
/// # struct Bar;
/// # impl From<Foo> for FooJson { fn from(_: Foo) -> FooJson { FooJson } }
/// # impl From<BarJson> for Bar { fn from(_: BarJson) -> Bar { Bar } }
/// json_api_call!(json "/foo": Foo as FooJson => BarJson as Bar);
/// ```
///
/// For this, we require:
/// ```ignore
/// Foo: TryInto<FooJson>
///     where <Foo as TryInto<FooJson>>::Error: Into<hapic::Error>
/// FooJson: Serialize
/// BarJson: Deserialize
/// BarJson: TryInto<Bar>
///     where <BarJson as TryInto<Bar>>::Error: Into<hapic::Error>
/// ```
///
/// # Not using the macros
///
/// Of course, you can implement [`SimpleApiCall`] or [`JsonApiCall`] yourself, however there isn't
/// much advantage, except for adding handling for non-2xx status codes.
///
/// If your API call is more complicated, you probably want to consider implementing [`ApiCall`]
/// (or, if you want almost no abstraction, [`SimpleApiCall`]).
#[macro_export]
macro_rules! json_api_call {
    (simple $(<$($a:lifetime),*>)? ($ApiCall:ty) $method:ident $url:literal : $Input:ty => $Output:ty) => {
        impl$(<$($a),*>)? $ApiCall for $Input {}
        $crate::json_api_call!(simple $(<$($a),*>)? $method $url : $Input => $Output);
    };

    (simple $(<$($a:lifetime),*>)? $method:ident $url:literal : $Input:ty => $Output:ty) => {
        impl$(<$($a),*>)? $crate::SimpleApiCall for $Input {
            type Output = $Output;

            fn method(&self) -> $crate::http::Method {
                $crate::http::Method::$method
            }

            fn uri(&self, endpoint: &str) -> std::string::String {
                let uri = String::with_capacity(endpoint.len() + $url.len());
                uri + endpoint + $url
            }
        }
    };

    (simple $(<$($a:lifetime),*>)? $(($ApiCall:ty))? $url:literal : $Input:ty => $Output:ty) => {
        $crate::json_api_call!(simple$(<$($a),*>)? $(($ApiCall))? POST $url: $Input => $Output);
    };

    (json $(<$($a:lifetime),*>)? ($ApiCall:ty) $method:ident $url:literal : $Input:ty as $JsonInput:ty => $JsonOutput:ty as $Output:ty) => {
        impl$(<$($a),*>)? $ApiCall for $Input {}
        $crate::json_api_call!(
            json$(<$($a),*>)? $method $url : $Input as $JsonInput => $JsonOutput as $Output
        );
    };

    (json $(<$($a:lifetime),*>)? $method:ident $url:literal : $Input:ty as $JsonInput:ty => $JsonOutput:ty as $Output:ty) => {
        impl$(<$($a),*>)? $crate::JsonApiCall for $Input {
            type Output = $Output;
            type JsonResponse = $JsonOutput;
            type JsonRequest = $JsonInput;

            fn method(&self) -> $crate::http::Method {
                $crate::http::Method::$method
            }

            fn uri(&self, endpoint: &str) -> std::string::String {
                let uri = String::with_capacity(endpoint.len() + $url.len());
                uri + endpoint + $url
            }

            fn try_into_request(self) -> std::result::Result<$JsonInput, $crate::Error> {
                Ok(self.try_into()?)
            }

            fn parse_json_response(
                status: $crate::http::StatusCode,
                content_type: Option<$crate::http::HeaderValue>,
                raw_resp: Vec<u8>,
                resp: $crate::serde_json::Result<Self::JsonResponse>,
            ) -> std::result::Result<$Output, $crate::Error> {
                if status.is_success() {
                    Ok(resp?.try_into()?)
                } else {
                    Err($crate::Error::HttpStatusNotSuccess{
                        status,
                        content_type,
                        body: raw_resp,
                    })
                }
            }
        }
    };

    (json $(<$($a:lifetime),*>)? $(($ApiCall:ty))? $url:literal : $Input:ty as $JsonInput:ty => $JsonOutput:ty as $Output:ty) => {
        $crate::json_api_call!(
            json $(<$($a),*>)? $(($ApiCall))? POST $url: $Input as $JsonInput => $JsonOutput as $Output
        );
    };

    (
        ApiCall: $ApiCall:ident;
        $(
            $(
                simple {$(
                    $(<$($a:lifetime),*>)? $($simple_method:ident)? $simple_url:literal : $SimpleInput:ty => $SimpleOutput:ty;
                )*}
            )?
            $(
                json {$(
                    $(<$($b:lifetime),*>)? $($json_method:ident)? $json_url:literal : $Input:ty as $JsonInput:ty => $JsonOutput:ty as $Output:ty;
                )*}
            )?
        );*
    ) => {$(
        $($(
            $crate::json_api_call!(simple $(<$($a),*>)? ($ApiCall) $($simple_method)? $simple_url: $SimpleInput => $SimpleOutput);
        )*)?
        $($(
            $crate::json_api_call!(json $(<$($b),*>)? ($ApiCall) $($json_method)? $json_url: $Input as $JsonInput => $JsonOutput as $Output);
        )*)?
    )*};
}

use transport::{ResponseBody, Transport};

pub struct Client<B, T: Transport<B>> {
    pub transport: T,
    pub phantom_body: PhantomData<B>,
    pub endpoint: Cow<'static, str>,
    pub authorization: Option<HeaderValue>,
    pub extra_headers: HeaderMap,
}

#[cfg(feature = "hyper")]
impl Client<hyper::Body, transport::HttpsTransport> {
    /// Create a new client using [`transport::HttpsTransport`] and [`hyper::Body`].
    pub fn new_https_client(
        endpoint: Cow<'static, str>,
    ) -> Client<hyper::Body, transport::HttpsTransport> {
        Client {
            transport: hyper::Client::builder().build(hyper_tls::HttpsConnector::new()),
            phantom_body: PhantomData,
            endpoint,
            authorization: None,
            extra_headers: HeaderMap::new(),
        }
    }

    /// Create a new client using [`transport::HttpsRetryTransport`] and [`hyper::Body`].
    pub fn new_https_retry_client(
        endpoint: Cow<'static, str>,
        retry_config: transport::retry::RetryConfig,
    ) -> Client<Vec<u8>, transport::HttpsRetryTransport> {
        Client {
            transport: transport::RetryTransport::new(
                hyper::Client::builder().build(hyper_tls::HttpsConnector::new()),
                retry_config,
            ),
            phantom_body: PhantomData,
            endpoint,
            authorization: None,
            extra_headers: HeaderMap::new(),
        }
    }
}

impl<B, T: Transport<B>> Client<B, T> {
    /// Create a new request builder based on this client.
    ///
    /// This should always be used as the base builder, since it includes the authorization and
    /// extra headers, and may include more parameters in the future.
    pub fn http_request_builder(&self) -> http::request::Builder {
        let mut builder = http::Request::builder();
        if let Some(authorization) = self.authorization.as_ref() {
            builder = builder.header(header::AUTHORIZATION, authorization);
        }
        for (header, value) in self.extra_headers.iter() {
            builder = builder.header(header, value);
        }
        builder
    }
}

#[derive(Debug)]
pub enum Error {
    Json(serde_json::Error),
    #[cfg(feature = "hyper")]
    Hyper(hyper::Error),
    HttpStatusNotSuccess {
        status: http::StatusCode,
        content_type: Option<http::HeaderValue>,
        body: Vec<u8>,
    },
    HttpNoBody,
    Other(Cow<'static, str>),
}

macro_rules! error_from {
    ($(impl From<$type:ty> for $Error:ident :: $Variant:ident);* $(;)?) => {
        $(
            impl From<$type> for $Error {
                fn from(err: $type) -> $Error {
                    $Error::$Variant(err)
                }
            }
        )*
    };
}

error_from!(
    impl From<serde_json::Error> for Error::Json;
);

#[cfg(feature = "hyper")]
error_from!(
    impl From<hyper::Error> for Error::Hyper;
);

impl From<std::convert::Infallible> for Error {
    fn from(_: std::convert::Infallible) -> Error {
        unreachable!()
    }
}

/// A JSON API call where the input and output types undergo no conversion.
///
/// This can be implemented manually, or by using:
/// `json_api_call!(simple "/endpoint": InputType => OutputType)`, or, to specify a custom method:
/// `json_api_call!(simple PATCH "/endpoint": InputType => OutputType)`.
///
/// Implementers of `SimpleApiCall`, automatically implement [`JsonApiCall`], therefore [`ApiCall`]
/// and therefore [`RawApiCall`].
pub trait SimpleApiCall: Serialize + Sized + Send {
    /// The output type of the call.
    type Output: for<'a> Deserialize<'a>;

    /// The HTTP request method.
    fn method(&self) -> Method {
        Method::POST
    }

    /// Generate the URI to make the HTTP POST request to.
    fn uri(&self, endpoint: &str) -> String;

    /// A hook used to modify the request before it's finalised. This is called directly before the
    /// `body` method on the builder is called.
    fn modify_request(&self, request_builder: http::request::Builder) -> http::request::Builder {
        request_builder
    }
}

impl<T: SimpleApiCall> JsonApiCall for T {
    type Output = <Self as SimpleApiCall>::Output;
    type JsonResponse = <Self as SimpleApiCall>::Output;

    type JsonRequest = Self;

    fn method(&self) -> Method {
        SimpleApiCall::method(self)
    }

    fn uri(&self, endpoint: &str) -> String {
        SimpleApiCall::uri(self, endpoint)
    }

    fn modify_request(&self, request_builder: http::request::Builder) -> http::request::Builder {
        SimpleApiCall::modify_request(self, request_builder)
    }

    fn try_into_request(self) -> Result<Self, Error> {
        Ok(self)
    }

    fn parse_json_response(
        status: StatusCode,
        content_type: Option<http::HeaderValue>,
        raw_resp: Vec<u8>,
        resp: serde_json::Result<Self::Output>,
    ) -> Result<Self::Output, Error> {
        if status.is_success() {
            Ok(resp?)
        } else {
            Err(Error::HttpStatusNotSuccess {
                status,
                content_type,
                body: raw_resp,
            })
        }
    }
}

/// A JSON API call. (See also: [`SimpleApiCall`])
///
/// This can be implemented manually, or by using the [`json_api_call`] macro.
///
/// Implementers of `JsonApiCall`, automatically implement [`ApiCall`] and therefore [`RawApiCall`].
pub trait JsonApiCall: Sized + Send {
    /// The output type of the call.
    type Output;

    /// The response type of the call, as is returned by the server.
    ///
    /// This is passed through [`Self::parse_json_response`] to generate the `Output` value.
    type JsonResponse: for<'a> Deserialize<'a>;

    /// The request that is sent to the server. `self` is converted to this type, using
    /// [`Self::try_into_request`] before making the API call.
    type JsonRequest: Serialize;

    /// The HTTP request method.
    fn method(&self) -> Method {
        Method::POST
    }

    /// Generate the URI to make the HTTP POST request to.
    fn uri(&self, endpoint: &str) -> String;

    /// A hook used to modify the request before it's finalised. This is called directly before the
    /// `body` method on the builder is called.
    fn modify_request(&self, request_builder: http::request::Builder) -> http::request::Builder {
        request_builder
    }

    /// Convert `self` to a [`Self::JsonRequest`]. This is called before making the HTTP POST
    /// request.
    fn try_into_request(self) -> Result<Self::JsonRequest, Error>;

    /// Convert a [`Self::JsonResponse`], as received from the server, into [`Self::Output`].
    fn parse_json_response(
        status: StatusCode,
        content_type: Option<http::HeaderValue>,
        raw_resp: Vec<u8>,
        resp: serde_json::Result<Self::JsonResponse>,
    ) -> Result<Self::Output, Error>;
}

#[async_trait::async_trait]
impl<T: JsonApiCall> ApiCall for T {
    type Output = <Self as JsonApiCall>::Output;
    type RequestBody = Vec<u8>;

    fn method(&self) -> Method {
        JsonApiCall::method(self)
    }

    fn uri(&self, endpoint: &str) -> String {
        JsonApiCall::uri(self, endpoint)
    }

    fn modify_request(&self, request_builder: http::request::Builder) -> http::request::Builder {
        JsonApiCall::modify_request(
            self,
            request_builder.header(http::header::CONTENT_TYPE, "application/json"),
        )
    }

    fn request_body(self) -> Result<Self::RequestBody, Error> {
        let req = self.try_into_request()?;
        Ok(serde_json::to_vec(&req)?)
    }

    async fn response<B: ResponseBody>(resp: http::Response<B>) -> Result<Self::Output, Error> {
        let status = resp.status();
        let content_type = resp.headers().get("Content-Type").cloned();
        let body_bytes = resp
            .into_body()
            .read_all()
            .await
            .map_err(|err| err.into())?;
        let resp: serde_json::Result<<Self as JsonApiCall>::JsonResponse> =
            serde_json::from_slice(body_bytes.as_ref());
        <Self as JsonApiCall>::parse_json_response(status, content_type, body_bytes.into(), resp)
    }
}

/// A generic API call. For a lower level interface, see [`RawApiCall`]. For JSON APIs, see
/// [`JsonApiCall`] and [`SimpleApiCall`].
#[async_trait::async_trait]
pub trait ApiCall: Sized + Send {
    /// The type of the request body.
    type RequestBody;

    /// The output type of the call.
    type Output;

    /// The HTTP request method.
    fn method(&self) -> Method {
        Method::POST
    }

    /// Generate the URI to make the HTTP POST request to.
    fn uri(&self, endpoint: &str) -> String;

    /// A hook used to modify the request before it's finalised. This is called directly before the
    /// `body` method on the builder is called.
    fn modify_request(&self, request_builder: http::request::Builder) -> http::request::Builder {
        request_builder
    }

    /// Convert `self` to a [`Self::RequestBody`]. This is called before making the HTTP POST
    /// request.
    fn request_body(self) -> Result<Self::RequestBody, Error>;

    /// Convert a [`http::Response`], as received from the server, into [`Self::Output`].
    async fn response<B: ResponseBody>(resp: http::Response<B>) -> Result<Self::Output, Error>;
}

#[async_trait::async_trait]
impl<C: ApiCall> RawApiCall for C {
    type Output = <C as ApiCall>::Output;

    type RequestBody = <C as ApiCall>::RequestBody;

    async fn request<B: From<Self::RequestBody> + Send, T: Transport<B>>(
        self,
        client: &Client<B, T>,
    ) -> Result<Self::Output, Error>
    where
        B: From<Self::RequestBody> + Sync,
    {
        let method = self.method();
        let uri = self.uri(&client.endpoint);
        let request = self
            .modify_request(client.http_request_builder().method(method).uri(uri))
            .body::<B>(self.request_body()?.into())
            .unwrap();
        let resp = client
            .transport
            .request(request)
            .await
            .map_err(|err| err.into())?;
        Self::response(resp).await
    }
}

/// The lowest level trait for API calls. You probably shouldn't implement it directly, instead
/// preferring [`ApiCall`], or, for JSON APIs, [`JsonApiCall`] and [`SimpleApiCall`].
///
/// If you do implement it directly, make sure you properly read the docs for the `request` method!
#[async_trait::async_trait]
pub trait RawApiCall: Sized {
    /// The type of the request body.
    type RequestBody;

    /// The output type of the call.
    type Output;

    /// Make a request using a client.
    ///
    /// It's super important to use the `client` value correctly. You should:
    /// - Use `client.endpoint` as the base of the URI.
    /// - Use `client.http_request_builder` as the base request builder, since this is garenteed to
    ///   use the other properties of the client.
    /// - Use `client.transport` to make the request.
    async fn request<B: From<Self::RequestBody> + Send, T: Transport<B>>(
        self,
        client: &Client<B, T>,
    ) -> Result<Self::Output, Error>
    where
        B: From<Self::RequestBody> + Sync;
}

#[cfg(test)]
mod test;