How does axum extractor injection works?

Hey there,

I'm curious about how Axum is doing it's dependency injection, like how you can pass zero or more parameters into a handler function and it will figure it out, I didn't even know it was possible to do that in Rust.

The example bellow gives a clue that it has something to do with the implementation of FromRequest but so far I couldn't make heads or tails of it.

// Handler that buffers the request body and returns it.
// This works because `Bytes` implements `FromRequest`
// and therefore can be used as an extractor.
// `String` and `StatusCode` both implement `IntoResponse` and
// therefore `Result<String, StatusCode>` also implements `IntoResponse`
async fn echo(body: Bytes) -> Result<String, StatusCode> {
    if let Ok(string) = String::from_utf8(body.to_vec()) {
    } else {
1 Like

The Handler trait is implemented for a lot of different function calls, using macros: Handler in axum::handler - Rust

The compiler will select the right implementation and use that, as long as all the parameters implement FromRequestParts, which I think is where you want to look for the magic, and the return type is the right type of future.

1 Like

Thanks ! That makes sense.

I wonder if there's a reason for it to be implemented this way, I noticed Actix also does the same thing, is it just a stylistic choice ? Its convenient but it looks like a lot of complexity on the background to make it work. I would probably just pass the request directly but maybe I'm being naive.

Once I had the same curiousness like u, and I got answer from here:

How to design an Axum server with test-friendliness in mind? Stackoverflow

wish it would be helpful.

1 Like

I guess adding the ability to define handlers this way is part of the point of Axum. You could always get the same effect by writing the Hyper service directly or with service_fn, which is what your Axum handler function eventually turns into.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.