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
//! # HTTP-API-PROBLEM
//!
//! [![crates.io](https://img.shields.io/crates/v/http-api-problem.svg)](https://crates.io/crates/http-api-problem)
//! [![docs.rs](https://docs.rs/http-api-problem/badge.svg)](https://docs.rs/http-api-problem)
//! [![downloads](https://img.shields.io/crates/d/http-api-problem.svg)](https://crates.io/crates/http-api-problem)
//! ![CI](https://github.com/chridou/http-api-problem/workflows/CI/badge.svg)
//! [![license-mit](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/chridou/http-api-problem/blob/master/LICENSE-MIT)
//! [![license-apache](http://img.shields.io/badge/license-APACHE-blue.svg)](https://github.com/chridou/http-api-problem/blob/master/LICENSE-APACHE)
//!
//! A library to create HTTP response content for APIs based on
//! [RFC7807](https://tools.ietf.org/html/rfc7807).
//!
//! ## Usage
//!
//! Get the latest version for your `Cargo.toml` from
//! [crates.io](https://crates.io/crates/http-api-problem).
//!
//! Add this to your crate root:
//!
//! ```rust
//! use http_api_problem;
//! ```
//!
//!  ## serde
//!
//! [HttpApiProblem] implements [Serialize] and [Deserialize] for
//! [HttpApiProblem].
//!
//! ## Examples
//!
//! ```rust
//! use http_api_problem::*;
//!
//! let p = HttpApiProblem::new(StatusCode::UNPROCESSABLE_ENTITY)
//!     .title("You do not have enough credit.")
//!     .detail("Your current balance is 30, but that costs 50.")
//!     .type_url("https://example.com/probs/out-of-credit")
//!     .instance("/account/12345/msgs/abc");
//!
//! assert_eq!(Some(StatusCode::UNPROCESSABLE_ENTITY), p.status);
//! assert_eq!(Some("You do not have enough credit."), p.title.as_deref());
//! assert_eq!(Some("Your current balance is 30, but that costs 50."), p.detail.as_deref());
//! assert_eq!(Some("https://example.com/probs/out-of-credit"), p.type_url.as_deref());
//! assert_eq!(Some("/account/12345/msgs/abc"), p.instance.as_deref());
//! ```
//!
//! There is also `TryFrom<u16>` implemented for [StatusCode]:
//!
//! ```rust
//! use http_api_problem::*;
//!
//! let p = HttpApiProblem::try_new(422).unwrap()
//!     .title("You do not have enough credit.")
//!     .detail("Your current balance is 30, but that costs 50.")
//!     .type_url("https://example.com/probs/out-of-credit")
//!     .instance("/account/12345/msgs/abc");
//!
//! assert_eq!(Some(StatusCode::UNPROCESSABLE_ENTITY), p.status);
//! assert_eq!(Some("You do not have enough credit."), p.title.as_deref());
//! assert_eq!(Some("Your current balance is 30, but that costs 50."), p.detail.as_deref());
//! assert_eq!(Some("https://example.com/probs/out-of-credit"), p.type_url.as_deref());
//! assert_eq!(Some("/account/12345/msgs/abc"), p.instance.as_deref());
//! ```
//!
//! ## Status Codes
//!
//! The specification does not require the [HttpApiProblem] to contain a
//! status code. Nevertheless this crate supports creating responses
//! for web frameworks. Responses require a status code. If no status code
//! was set on the [HttpApiProblem] `500 - Internal Server Error` will be
//! used as a fallback. This can be easily avoided by only using those constructor
//! functions which require a [StatusCode].
//!
//! ## Features
//!
//! ### JsonSchema
//!
//! The feature `json-schema` enables a derived implementation for
//! JsonSchema, via `schemars`.
//!
//! ### Web Frameworks
//!
//! There are multiple features to integrate with web frameworks:
//!
//! * `axum`
//! * `warp`
//! * `hyper`
//! * `actix-web`
//! * `salvo`
//! * `tide`
//! * `rocket (v0.5.0-rc1)`
//!
//! These mainly convert the `HttpApiProblem` to response types of
//! the frameworks and implement traits to integrate with the frameworks
//! error handling.
//!
//! Additionally, the feature `rocket-okapi` (which implies the features
//! `rocket` and `json-schema`) implements `rocket_okapi`'s `OpenApiResponder`
//! for the json schema generated by the `json-schema` feature.
//!
//! ### ApiError
//!
//! The feature `api-error` enables a structure which can be
//! return from "api handlers" that generate responses and can be
//! converted into an `HttpApiProblem`.
//!
//! ## License
//!
//! `http-api-problem` is primarily distributed under the terms of both the MIT
//! license and the Apache License (Version 2.0).
//!
//! Copyright (c) 2017 Christian Douven.
use std::convert::TryInto;
use std::error::Error;
use std::fmt;

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

#[cfg(feature = "api-error")]
mod api_error;
#[cfg(feature = "api-error")]
pub use api_error::*;

#[cfg(feature = "json-schema")]
use schemars::JsonSchema;

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

#[cfg(feature = "actix-web")]
use actix_web_crate as actix_web;

#[cfg(feature = "salvo")]
use salvo;

#[cfg(feature = "axum")]
use axum_core;

pub use http::status::{InvalidStatusCode, StatusCode};

/// The recommended media type when serialized to JSON
///
/// "application/problem+json"
pub static PROBLEM_JSON_MEDIA_TYPE: &str = "application/problem+json";

/// Description of a problem that can be returned by an HTTP API
/// based on [RFC7807](https://tools.ietf.org/html/rfc7807)
///
/// # Example
///
/// ```javascript
/// {
///    "type": "https://example.com/probs/out-of-credit",
///    "title": "You do not have enough credit.",
///    "detail": "Your current balance is 30, but that costs 50.",
///    "instance": "/account/12345/msgs/abc",
/// }
/// ```
///
/// # Purpose
///
/// The purpose of [HttpApiProblem] is to generate a meaningful response
/// for clients. It is not intended to be used as a replacement
/// for a proper `Error` struct within applications.
///
/// For a struct which can be returned by HTTP handlers use [ApiError] which
/// can be enabled with the feature toggle `api-error`. [ApiError] can be directly
/// converted into [HttpApiProblem].
///
/// # Status Codes and Responses
///
/// Prefer to use one of the constructors which
/// ensure that a [StatusCode] is set. If no [StatusCode] is
/// set and a transformation to a response of a web framework
/// is made a [StatusCode] becomes mandatory which in this case will
/// default to `500`.
///
/// When receiving an [HttpApiProblem] there might be an invalid
/// [StatusCode] contained. In this case the `status` field will be empty.
/// This is a trade off so that the recipient does not have to deal with
/// another error and can still have access to the remaining fields of the
/// struct.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
#[cfg_attr(
    feature = "json-schema",
    schemars(
        description = "Description of a problem that can be returned by an HTTP API based on [RFC7807](https://tools.ietf.org/html/rfc7807)"
    )
)]
pub struct HttpApiProblem {
    /// A URI reference [RFC3986](https://tools.ietf.org/html/rfc3986) that identifies the
    /// problem type.  This specification encourages that, when
    /// dereferenced, it provide human-readable documentation for the
    /// problem type (e.g., using HTML [W3C.REC-html5-20141028]).  When
    /// this member is not present, its value is assumed to be
    /// "about:blank".
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "json-schema",
        schemars(
            description = "A [RFC3986 URI reference](https://tools.ietf.org/html/rfc3986) that identifies the problem type. When dereferenced, it may provide human-readable documentation for the problem type."
        )
    )]
    pub type_url: Option<String>,

    /// The HTTP status code [RFC7231, Section 6](https://tools.ietf.org/html/rfc7231#section-6)
    /// generated by the origin server for this occurrence of the problem.
    #[serde(default)]
    #[serde(with = "custom_http_status_serialization")]
    #[cfg_attr(feature = "json-schema", schemars(with = "u16"))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<StatusCode>,

    /// A short, human-readable summary of the problem
    /// type. It SHOULD NOT change from occurrence to occurrence of the
    /// problem, except for purposes of localization (e.g., using
    /// proactive content negotiation;
    /// see [RFC7231, Section 3.4](https://tools.ietf.org/html/rfc7231#section-3.4).
    #[cfg_attr(
        feature = "json-schema",
        schemars(
            description = "A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence of the problem."
        )
    )]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// A human-readable explanation specific to this
    /// occurrence of the problem.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,

    /// A URI reference that identifies the specific
    /// occurrence of the problem.  It may or may not yield further
    /// information if dereferenced.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,

    /// Additional fields that must be JSON values
    ///
    /// These values get serialized into the JSON
    /// on top level.
    #[serde(flatten)]
    additional_fields: HashMap<String, serde_json::Value>,
}

impl HttpApiProblem {
    /// Creates a new instance with the given [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new(StatusCode::INTERNAL_SERVER_ERROR);
    ///
    /// assert_eq!(Some(StatusCode::INTERNAL_SERVER_ERROR), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn new<T: Into<StatusCode>>(status: T) -> Self {
        Self::empty().status(status)
    }

    /// Creates a new instance with the given [StatusCode].
    ///
    /// Fails if the argument can not be converted into a [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::try_new(500).unwrap();
    ///
    /// assert_eq!(Some(StatusCode::INTERNAL_SERVER_ERROR), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn try_new<T: TryInto<StatusCode>>(status: T) -> Result<Self, InvalidStatusCode>
    where
        T::Error: Into<InvalidStatusCode>,
    {
        let status = status.try_into().map_err(|e| e.into())?;
        Ok(Self::new(status))
    }

    /// Creates a new instance with `title` derived from a [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_title(StatusCode::NOT_FOUND);
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(Some("Not Found"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_title<T: Into<StatusCode>>(status: T) -> Self {
        let status = status.into();
        Self::new(status).title(
            status
                .canonical_reason()
                .unwrap_or("<unknown status code>")
                .to_string(),
        )
    }

    /// Creates a new instance with `title` derived from a [StatusCode].
    ///
    /// Fails if the argument can not be converted into a [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::try_with_title(404).unwrap();
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(Some("Not Found"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn try_with_title<T: TryInto<StatusCode>>(status: T) -> Result<Self, InvalidStatusCode>
    where
        T::Error: Into<InvalidStatusCode>,
    {
        let status = status.try_into().map_err(|e| e.into())?;
        Ok(Self::with_title(status))
    }

    /// Creates a new instance with the `title` and `type_url` derived from the
    /// [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::with_title_and_type(StatusCode::SERVICE_UNAVAILABLE);
    ///
    /// assert_eq!(Some(StatusCode::SERVICE_UNAVAILABLE), p.status);
    /// assert_eq!(Some("Service Unavailable"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(Some("https://httpstatuses.com/503".to_string()), p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn with_title_and_type<T: Into<StatusCode>>(status: T) -> Self {
        let status = status.into();
        Self::with_title(status).type_url(format!("https://httpstatuses.com/{}", status.as_u16()))
    }

    /// Creates a new instance with the `title` and `type_url` derived from the
    /// [StatusCode].
    ///
    /// Fails if the argument can not be converted into a [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::try_with_title_and_type(503).unwrap();
    ///
    /// assert_eq!(Some(StatusCode::SERVICE_UNAVAILABLE), p.status);
    /// assert_eq!(Some("Service Unavailable"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(Some("https://httpstatuses.com/503".to_string()), p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn try_with_title_and_type<T: TryInto<StatusCode>>(
        status: T,
    ) -> Result<Self, InvalidStatusCode>
    where
        T::Error: Into<InvalidStatusCode>,
    {
        let status = status.try_into().map_err(|e| e.into())?;

        Ok(Self::with_title_and_type(status))
    }

    /// Creates a new instance without any field set.
    ///
    /// Prefer to use one of the other constructors which
    /// ensure that a [StatusCode] is set. If no [StatusCode] is
    /// set and a transformation to a response of a web framework
    /// is made a [StatusCode] becomes mandatory which in this case will
    /// default to `500`.
    pub fn empty() -> Self {
        HttpApiProblem {
            type_url: None,
            status: None,
            title: None,
            detail: None,
            instance: None,
            additional_fields: Default::default(),
        }
    }

    /// Sets the `status`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new(StatusCode::NOT_FOUND).title("Error");
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(Some("Error"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn status<T: Into<StatusCode>>(mut self, status: T) -> Self {
        self.status = Some(status.into());
        self
    }

    /// Sets the `type_url`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new(StatusCode::NOT_FOUND).type_url("http://example.com/my/real_error");
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(Some("http://example.com/my/real_error".to_string()), p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn type_url<T: Into<String>>(mut self, type_url: T) -> Self {
        self.type_url = Some(type_url.into());
        self
    }

    /// Tries to set the `status`
    ///
    /// Fails if the argument can not be converted into a [StatusCode].
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::try_new(404).unwrap().title("Error");
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(Some("Error"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn try_status<T: TryInto<StatusCode>>(
        mut self,
        status: T,
    ) -> Result<Self, InvalidStatusCode>
    where
        T::Error: Into<InvalidStatusCode>,
    {
        self.status = Some(status.try_into().map_err(|e| e.into())?);
        Ok(self)
    }

    /// Sets the `title`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new(StatusCode::NOT_FOUND).title("Another Error");
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(Some("Another Error"), p.title.as_deref());
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn title<T: Into<String>>(mut self, title: T) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the `detail`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new(StatusCode::NOT_FOUND).detail("a detailed description");
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(Some("a detailed description".to_string()), p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(None, p.instance);
    /// ```
    pub fn detail<T: Into<String>>(mut self, detail: T) -> HttpApiProblem {
        self.detail = Some(detail.into());
        self
    }

    /// Sets the `instance`
    ///
    /// #Example
    ///
    /// ```rust
    /// use http_api_problem::*;
    ///
    /// let p = HttpApiProblem::new(StatusCode::NOT_FOUND).instance("/account/1234/withdraw");
    ///
    /// assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
    /// assert_eq!(None, p.title);
    /// assert_eq!(None, p.detail);
    /// assert_eq!(None, p.type_url);
    /// assert_eq!(Some("/account/1234/withdraw".to_string()), p.instance);
    /// ```
    pub fn instance<T: Into<String>>(mut self, instance: T) -> HttpApiProblem {
        self.instance = Some(instance.into());
        self
    }

    /// Add a value that must be serializable.
    ///
    /// The key must not be one of the field names of this struct.
    ///
    /// These values get serialized into the JSON
    /// on top level.
    pub fn try_value<K, V>(
        mut self,
        key: K,
        value: &V,
    ) -> Result<Self, Box<dyn Error + Send + Sync + 'static>>
    where
        V: Serialize,
        K: Into<String>,
    {
        self.try_set_value(key, value)?;
        Ok(self)
    }

    /// Add a value that must be serializable.
    ///
    /// The key must not be one of the field names of this struct.
    /// If the key is a field name or the value is not serializable nothing happens.
    ///
    /// These values get serialized into the JSON
    /// on top level.
    pub fn value<K, V>(mut self, key: K, value: &V) -> Self
    where
        V: Serialize,
        K: Into<String>,
    {
        self.set_value(key, value);
        self
    }

    /// Add a value that must be serializable.
    ///
    /// The key must not be one of the field names of this struct.
    /// If the key is a field name or the value is not serializable nothing happens.
    ///
    /// These values get serialized into the JSON
    /// on top level.
    pub fn set_value<K, V>(&mut self, key: K, value: &V)
    where
        V: Serialize,
        K: Into<String>,
    {
        let _ = self.try_set_value(key, value);
    }

    /// Returns the deserialized field for the given key.
    ///
    /// If the key does not exist or the field is not deserializable to
    /// the target type `None` is returned
    pub fn get_value<K, V>(&self, key: &str) -> Option<V>
    where
        V: DeserializeOwned,
    {
        self.json_value(key)
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    pub fn try_set_value<K, V>(
        &mut self,
        key: K,
        value: &V,
    ) -> Result<(), Box<dyn Error + Send + Sync + 'static>>
    where
        V: Serialize,
        K: Into<String>,
    {
        let key: String = key.into();
        match key.as_ref() {
            "type" => return Err("'type' is a reserved field name".into()),
            "status" => return Err("'status' is a reserved field name".into()),
            "title" => return Err("'title' is a reserved field name".into()),
            "detail" => return Err("'detail' is a reserved field name".into()),
            "instance" => return Err("'instance' is a reserved field name".into()),
            "additional_fields" => {
                return Err("'additional_fields' is a reserved field name".into());
            }
            _ => (),
        }
        let serialized = serde_json::to_value(value).map_err(|err| err.to_string())?;
        self.additional_fields.insert(key, serialized);
        Ok(())
    }

    /// Returns a reference to the serialized fields
    ///
    /// If the key does not exist or the field is not deserializable to
    /// the target type `None` is returned
    pub fn additional_fields(&self) -> &HashMap<String, Value> {
        &self.additional_fields
    }

    /// Returns a mutable reference to the serialized fields
    ///
    /// If the key does not exist or the field is not deserializable to
    /// the target type `None` is returned
    pub fn additional_fields_mut(&mut self) -> &mut HashMap<String, Value> {
        &mut self.additional_fields
    }

    pub fn keys<K, V>(&self) -> impl Iterator<Item = &String>
    where
        V: DeserializeOwned,
    {
        self.additional_fields.keys()
    }

    /// Returns the `serde_json::Value` for the given key if the key exists.
    pub fn json_value(&self, key: &str) -> Option<&serde_json::Value> {
        self.additional_fields.get(key)
    }

    /// Serialize to a JSON `Vec<u8>`
    pub fn json_bytes(&self) -> Vec<u8> {
        serde_json::to_vec(self).unwrap()
    }

    /// Serialize to a JSON `String`
    pub fn json_string(&self) -> String {
        serde_json::to_string(self).unwrap()
    }

    /// Creates a [hyper] response.
    ///
    /// If status is `None` `500 - Internal Server Error` is the
    /// default.
    ///
    /// Requires the `hyper` feature
    #[cfg(feature = "hyper")]
    pub fn to_hyper_response(&self) -> hyper::Response<hyper::Body> {
        use hyper::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE};
        use hyper::*;

        let json = self.json_bytes();
        let length = json.len() as u64;

        let (mut parts, body) = Response::new(json.into()).into_parts();

        parts.headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        parts.headers.insert(
            CONTENT_LENGTH,
            HeaderValue::from_str(&length.to_string()).unwrap(),
        );
        parts.status = self
            .status_or_internal_server_error()
            .as_u16()
            .try_into()
            .unwrap_or(hyper::StatusCode::INTERNAL_SERVER_ERROR);

        Response::from_parts(parts, body)
    }

    /// Creates an axum [Response](axum_core::response::Response).
    ///
    /// If status is `None` `500 - Internal Server Error` is the
    /// default.
    ///
    /// Requires the `axum` feature
    #[cfg(feature = "axum")]
    pub fn to_axum_response(&self) -> axum_core::response::Response {
        use axum_core::response::IntoResponse;
        use http::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE};

        let json = self.json_bytes();
        let length = json.len() as u64;

        let status = self.status_or_internal_server_error();

        let mut response = (status, json).into_response();

        *response.status_mut() = self.status_or_internal_server_error();

        response.headers_mut().insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        response.headers_mut().insert(
            CONTENT_LENGTH,
            HeaderValue::from_str(&length.to_string()).unwrap(),
        );

        response
    }

    /// Creates an `actix` response.
    ///
    /// If status is `None` or not convertible
    /// to an actix status `500 - Internal Server Error` is the
    /// default.
    ///
    /// Requires the `actix-web` feature
    #[cfg(feature = "actix-web")]
    pub fn to_actix_response(&self) -> actix_web::HttpResponse {
        let effective_status = self.status_or_internal_server_error();
        let actix_status = actix_web::http::StatusCode::from_u16(effective_status.as_u16())
            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

        let json = self.json_bytes();

        actix_web::HttpResponse::build(actix_status)
            .append_header((
                actix_web::http::header::CONTENT_TYPE,
                PROBLEM_JSON_MEDIA_TYPE,
            ))
            .body(json)
    }

    /// Creates a `rocket` response.
    ///
    /// If status is `None` `500 - Internal Server Error` is the
    /// default.
    ///
    /// Requires the `rocket` feature
    #[cfg(feature = "rocket")]
    pub fn to_rocket_response(&self) -> rocket::Response<'static> {
        use rocket::http::ContentType;
        use rocket::http::Status;
        use rocket::Response;
        use std::io::Cursor;

        let content_type: ContentType = PROBLEM_JSON_MEDIA_TYPE.parse().unwrap();
        let json = self.json_bytes();
        let response = Response::build()
            .status(Status {
                code: self.status_code_or_internal_server_error(),
            })
            .sized_body(json.len(), Cursor::new(json))
            .header(content_type)
            .finalize();

        response
    }

    /// Creates a [salvo] response.
    ///
    /// If status is `None` `500 - Internal Server Error` is the
    /// default.
    ///
    /// Requires the `salvo` feature
    #[cfg(feature = "salvo")]
    pub fn to_salvo_response(&self) -> salvo::Response {
        use salvo::hyper::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE};
        use salvo::hyper::*;

        let json = self.json_bytes();
        let length = json.len() as u64;

        let (mut parts, body) = Response::new(json.into()).into_parts();

        parts.headers.insert(
            CONTENT_TYPE,
            HeaderValue::from_static(PROBLEM_JSON_MEDIA_TYPE),
        );
        parts.headers.insert(
            CONTENT_LENGTH,
            HeaderValue::from_str(&length.to_string()).unwrap(),
        );
        parts.status = self
            .status_or_internal_server_error()
            .as_u16()
            .try_into()
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

        Response::from_parts(parts, body).into()
    }

    /// Creates a [tide] response.
    ///
    /// If status is `None` `500 - Internal Server Error` is the
    /// default.
    ///
    /// Requires the `tide` feature
    #[cfg(feature = "tide")]
    pub fn to_tide_response(&self) -> tide::Response {
        let json = self.json_bytes();
        let length = json.len() as u64;

        tide::Response::builder(self.status_code_or_internal_server_error())
            .body(json)
            .header("Content-Length", length.to_string())
            .content_type(PROBLEM_JSON_MEDIA_TYPE)
            .build()
    }

    #[allow(dead_code)]
    fn status_or_internal_server_error(&self) -> StatusCode {
        self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
    }

    #[allow(dead_code)]
    fn status_code_or_internal_server_error(&self) -> u16 {
        self.status_or_internal_server_error().as_u16()
    }

    // Deprecations

    #[deprecated(since = "0.50.0", note = "please use `with_title` instead")]
    pub fn with_title_from_status<T: Into<StatusCode>>(status: T) -> Self {
        Self::with_title(status)
    }
    #[deprecated(since = "0.50.0", note = "please use `with_title_and_type` instead")]
    pub fn with_title_and_type_from_status<T: Into<StatusCode>>(status: T) -> Self {
        Self::with_title_and_type(status)
    }
    #[deprecated(since = "0.50.0", note = "please use `status` instead")]
    pub fn set_status<T: Into<StatusCode>>(self, status: T) -> Self {
        self.status(status)
    }
    #[deprecated(since = "0.50.0", note = "please use `title` instead")]
    pub fn set_title<T: Into<String>>(self, title: T) -> Self {
        self.title(title)
    }
    #[deprecated(since = "0.50.0", note = "please use `detail` instead")]
    pub fn set_detail<T: Into<String>>(self, detail: T) -> Self {
        self.detail(detail)
    }
    #[deprecated(since = "0.50.0", note = "please use `type_url` instead")]
    pub fn set_type_url<T: Into<String>>(self, type_url: T) -> Self {
        self.type_url(type_url)
    }
    #[deprecated(since = "0.50.0", note = "please use `instance` instead")]
    pub fn set_instance<T: Into<String>>(self, instance: T) -> Self {
        self.instance(instance)
    }
}

impl fmt::Display for HttpApiProblem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(status) = self.status {
            write!(f, "{}", status)?;
        } else {
            write!(f, "<no status>")?;
        }

        match (self.title.as_ref(), self.detail.as_ref()) {
            (Some(title), Some(detail)) => return write!(f, " - {} - {}", title, detail),
            (Some(title), None) => return write!(f, " - {}", title),
            (None, Some(detail)) => return write!(f, " - {}", detail),
            (None, None) => (),
        }

        if let Some(type_url) = self.type_url.as_ref() {
            return write!(f, " - {}", type_url);
        }

        Ok(())
    }
}

impl Error for HttpApiProblem {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

impl From<StatusCode> for HttpApiProblem {
    fn from(status: StatusCode) -> HttpApiProblem {
        HttpApiProblem::new(status)
    }
}

impl From<std::convert::Infallible> for HttpApiProblem {
    fn from(error: std::convert::Infallible) -> HttpApiProblem {
        match error {}
    }
}

/// Creates an [hyper::Response] from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "hyper")]
pub fn into_hyper_response<T: Into<HttpApiProblem>>(what: T) -> hyper::Response<hyper::Body> {
    let problem: HttpApiProblem = what.into();
    problem.to_hyper_response()
}

#[cfg(feature = "hyper")]
impl From<HttpApiProblem> for hyper::Response<hyper::Body> {
    fn from(problem: HttpApiProblem) -> hyper::Response<hyper::Body> {
        problem.to_hyper_response()
    }
}

/// Creates an axum [Response](axum_core::response::Response) from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
///
/// Requires the `axum` feature
#[cfg(feature = "axum")]
pub fn into_axum_response<T: Into<HttpApiProblem>>(what: T) -> axum_core::response::Response {
    let problem: HttpApiProblem = what.into();
    problem.to_axum_response()
}

#[cfg(feature = "axum")]
impl From<HttpApiProblem> for axum_core::response::Response {
    fn from(problem: HttpApiProblem) -> axum_core::response::Response {
        problem.to_axum_response()
    }
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for HttpApiProblem {
    fn into_response(self) -> axum_core::response::Response {
        self.into()
    }
}

// Creates an `actix::HttpResponse` from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "actix-web")]
pub fn into_actix_response<T: Into<HttpApiProblem>>(what: T) -> actix_web::HttpResponse {
    let problem: HttpApiProblem = what.into();
    problem.to_actix_response()
}

#[cfg(feature = "actix-web")]
impl From<HttpApiProblem> for actix_web::HttpResponse {
    fn from(problem: HttpApiProblem) -> actix_web::HttpResponse {
        problem.to_actix_response()
    }
}

/// Creates an `rocket::Response` from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "rocket")]
pub fn into_rocket_response<T: Into<HttpApiProblem>>(what: T) -> ::rocket::Response<'static> {
    let problem: HttpApiProblem = what.into();
    problem.to_rocket_response()
}

#[cfg(feature = "rocket")]
impl From<HttpApiProblem> for ::rocket::Response<'static> {
    fn from(problem: HttpApiProblem) -> ::rocket::Response<'static> {
        problem.to_rocket_response()
    }
}

#[cfg(feature = "rocket")]
impl<'r> ::rocket::response::Responder<'r, 'static> for HttpApiProblem {
    fn respond_to(self, _request: &::rocket::Request) -> ::rocket::response::Result<'static> {
        Ok(self.into())
    }
}

#[cfg(feature = "rocket-okapi")]
impl rocket_okapi::response::OpenApiResponderInner for HttpApiProblem {
    fn responses(
        gen: &mut rocket_okapi::gen::OpenApiGenerator,
    ) -> rocket_okapi::Result<rocket_okapi::okapi::openapi3::Responses> {
        let mut responses = rocket_okapi::okapi::openapi3::Responses::default();
        let schema = gen.json_schema::<HttpApiProblem>();
        rocket_okapi::util::add_default_response_schema(
            &mut responses,
            PROBLEM_JSON_MEDIA_TYPE,
            schema,
        );
        Ok(responses)
    }
}

#[cfg(feature = "warp")]
impl warp::reject::Reject for HttpApiProblem {}

/// Creates a [salvo::Response] from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "salvo")]
pub fn into_salvo_response<T: Into<HttpApiProblem>>(what: T) -> salvo::Response {
    let problem: HttpApiProblem = what.into();
    problem.to_salvo_response()
}

#[cfg(feature = "salvo")]
impl From<HttpApiProblem> for salvo::Response {
    fn from(problem: HttpApiProblem) -> salvo::Response {
        problem.to_salvo_response()
    }
}

/// Creates a [tide::Response] from something that can become an
/// `HttpApiProblem`.
///
/// If status is `None` `500 - Internal Server Error` is the
/// default.
#[cfg(feature = "tide")]
pub fn into_tide_response<T: Into<HttpApiProblem>>(what: T) -> tide::Response {
    let problem: HttpApiProblem = what.into();
    problem.to_tide_response()
}

#[cfg(feature = "tide")]
impl From<HttpApiProblem> for tide::Response {
    fn from(problem: HttpApiProblem) -> tide::Response {
        problem.to_tide_response()
    }
}

mod custom_http_status_serialization {
    use http::StatusCode;
    use serde::{Deserialize, Deserializer, Serializer};
    use std::convert::TryFrom;

    pub fn serialize<S>(status: &Option<StatusCode>, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if let Some(ref status_code) = *status {
            return s.serialize_u16(status_code.as_u16());
        }
        s.serialize_none()
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<StatusCode>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: Option<u16> = Option::deserialize(deserializer)?;
        if let Some(numeric_status_code) = s {
            // If the status code numeral is invalid we simply return None.
            // This is a trade off to guarantee that the client can still
            // have access to the rest of the problem struct instead of
            // having to deal with an error caused by trying to deserialize an invalid status
            // code. Additionally the received response still contains a status code.
            let status_code = StatusCode::try_from(numeric_status_code).ok();
            return Ok(status_code);
        }

        Ok(None)
    }
}

#[cfg(test)]
mod test;