chridou / http-api-problem

A problem type to be returned by HTTP APIs
Apache License 2.0
53 stars 12 forks source link

`axum` compat: `impl IntoResponse` #49

Closed coriolinus closed 8 months ago

coriolinus commented 9 months ago

axum handles responses based on the IntoResponse trait. The benefit of this is composable responses; a handler can return a status code, body data, headers, or a combination of the above, and the response gets constructed appropriately.

There should be an implementation like

#[cfg(feature = "axum")]
impl axum::response::IntoResponse for HttpApiProblem {
    fn into_response(self) -> axum::response::Response {
        let status = self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        (
            status,
            [(http::header::CONTENT_TYPE, "application/problem+json")],
            axum::response::Json(self),
        ).into_response()
    }
}

The benefit of this implementation is that it automatically sets the status and content-type of the response, as well as json-encoding the error in the body; otherwise, it is easy for implementors to neglect to do all those things every time.

chridou commented 8 months ago

Hi! this is already implemented.

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

That's good news! Does it also set the status and content type? I didn't find the implementation when browsing; only the explicit to_axum_response method.

awaltert commented 8 months ago

Hi @coriolinus, yes the implementation sets the status and content type fields because it uses the From<HttpApiProblem> implementation that calls the to_axum_response method.

coriolinus commented 8 months ago

Excellent! Thanks, and sorry for having wasted your time.