Axum: Return tuple with HTTP StatusCode and optional value: Option
⚓ Rust 📅 2025-06-03 👤 surdeus 👁️ 11I am writing an Axum REST API and am curious how I can return an optional struct. I'm using the tuple return value, which allows me to also return an HTTP StatusCode enum value.
When I write an axum route handler that looks like the following example, I get a compiler error.
async fn item_post() -> (StatusCode, Option<Json<MyStruct>>) {
}
the trait bound
fn(Option<Json<MyStruct>>) -> ... {mystruct_post}: Handler<_, _>is not satisfied
Consider using#[axum::debug_handler]to improve the error message
the following other types implement traitHandler<T, S>:
Layered<L, H, T, S>implementsHandler<T, S>
MethodRouter<S>implementsHandler<(), S>
I also tried this:
async fn item_post() -> (StatusCode, impl IntoResponse) {
}
But this resulted in:
impl Traitis not allowed in bounds
impl Traitis only allowed in arguments and return types of functions and methods
cannot define inherentimplfor foreign type
Apparently you can only use impl IntoResponse as the top-level return type, not inside a tuple.
Question: Is there a proper way to return an optional struct from an axum route handler?
2 posts - 2 participants
🏷️ rust_feed