Skip to main content

ProblemFormat

Enum ProblemFormat 

Source
pub enum ProblemFormat {
    ProblemJson,
    Json,
}
Expand description

The media type a Problem response is served as: the RFC 9457 default application/problem+json, or plain application/json for clients that explicitly prefer it.

This is the opt-in content negotiation half of the problem feature. Problem’s plain IntoResponse impl always emits application/problem+json; nothing changes for existing users. To negotiate, either extract ProblemFormat in a handler (it implements FromRequestParts infallibly, reading the Accept headers) and finish with Problem::into_response_with, or call Problem::into_response_for with the request’s HeaderMap directly.

Both formats serve byte-identical JSON bodies; only the Content-Type header differs. Default is ProblemFormat::ProblemJson.

§Example

use axum::{http::StatusCode, response::Response, routing::get, Router};
use axum_api_kit::{Problem, ProblemFormat};

// Accept: application/json          -> Content-Type: application/json
// Accept: */* (or no Accept header) -> Content-Type: application/problem+json
async fn not_found(format: ProblemFormat) -> Response {
    Problem::new(StatusCode::NOT_FOUND, "Not Found").into_response_with(format)
}

let app: Router = Router::new().route("/missing", get(not_found));

Variants§

§

ProblemJson

Serve Content-Type: application/problem+json (the RFC 9457 media type, and the default in every ambiguous case).

§

Json

Serve Content-Type: application/json, for clients whose Accept header strictly prefers plain JSON.

Implementations§

Source§

impl ProblemFormat

Source

pub fn negotiate(headers: &HeaderMap) -> Self

Chooses the response format from a request’s Accept headers.

This is a minimal, hand-rolled matcher, deliberately not a full RFC 9110 implementation. The rules:

  1. Recognized media ranges are application/problem+json, application/json, application/*, and */* (ASCII case-insensitive, across all Accept headers). Every other range, including other +json suffix types, is ignored.
  2. A range’s weight is its q parameter (default 1). Parameters other than the first q are ignored. A range whose q value does not parse per the RFC 9110 qvalue grammar (0 to 1 with at most three decimals) is ignored entirely.
  3. Each of the two servable types takes its weight from the most specific matching range (an exact match beats application/*, which beats */*); among equally specific matches the highest q wins.
  4. ProblemFormat::Json is returned only when plain application/json ends up with a strictly higher weight than application/problem+json. Everything else (no Accept header, */*, application/*, equal weights, q=0 on both, unparseable headers) returns ProblemFormat::ProblemJson.
Acceptresult
(absent)problem+json
*/*problem+json
application/*problem+json
application/jsonplain JSON
application/problem+jsonproblem+json
application/json, */*problem+json (tie at q=1)
application/json;q=0.9, application/problem+json;q=0.5plain JSON
application/problem+json, application/jsonproblem+json (tie)
text/htmlproblem+json (neither matched)
§Example
use axum::http::{header, HeaderMap, HeaderValue};
use axum_api_kit::ProblemFormat;

let mut headers = HeaderMap::new();
headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
assert_eq!(ProblemFormat::negotiate(&headers), ProblemFormat::Json);

assert_eq!(
    ProblemFormat::negotiate(&HeaderMap::new()),
    ProblemFormat::ProblemJson
);
Source

pub fn content_type(self) -> &'static str

The Content-Type value this format serves.

§Example
use axum_api_kit::{ProblemFormat, APPLICATION_PROBLEM_JSON};

assert_eq!(ProblemFormat::ProblemJson.content_type(), APPLICATION_PROBLEM_JSON);
assert_eq!(ProblemFormat::Json.content_type(), "application/json");

Trait Implementations§

Source§

impl Clone for ProblemFormat

Source§

fn clone(&self) -> ProblemFormat

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for ProblemFormat

Source§

impl Debug for ProblemFormat

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ProblemFormat

Source§

fn default() -> ProblemFormat

Returns the “default value” for a type. Read more
Source§

impl Eq for ProblemFormat

Source§

impl<S> FromRequestParts<S> for ProblemFormat
where S: Send + Sync,

Source§

type Rejection = Infallible

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( parts: &mut Parts, _state: &S, ) -> Result<Self, Self::Rejection>

Perform the extraction.
Source§

impl PartialEq for ProblemFormat

Source§

fn eq(&self, other: &ProblemFormat) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for ProblemFormat

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more