Axum: Return tuple with HTTP StatusCode and optional value: Option

⚓ rust    📅 2025-06-03    👤 surdeus    👁️ 2      

surdeus

I 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 trait Handler<T, S>:
Layered<L, H, T, S> implements Handler<T, S>
MethodRouter<S> implements Handler<(), S>

I also tried this:

async fn item_post() -> (StatusCode, impl IntoResponse) {
}

But this resulted in:

impl Trait is not allowed in bounds
impl Trait is only allowed in arguments and return types of functions and methods
cannot define inherent impl for foreign type

Apparently you can only use impl IntoResponse as the top-level return type, not inside a tuple.

:light_bulb: Question: Is there a proper way to return an optional struct from an axum route handler?

2 posts - 2 participants

Read full topic

🏷️ rust_feed