Test request builder

Learn how Request builder builds the exact HTTP request a test sends through oneshot with its method URI headers and body set piece by piece

Request::builder() is the way a test builds the HTTP request it sends through oneshot. A builder is an object that collects the parts of a value one call at a time and then produces the finished value at the end. The request builder collects the method, the URI, the headers, and the body, and its .body() call finishes the job and hands back a complete Request. Its one job is to let a test say exactly what the client would send, piece by piece, without writing raw HTTP text.

Where This Fits

The oneshot page showed the call that sends a request, and every example on that page built its request with Request::builder(). This page takes the builder apart. The request is half of every integration test, and a test that cannot build the right request cannot check the right behaviour. The builder is the tool that makes the request exact: the right method, the right path, the right headers, and the right body.

Think of ordering food by filling in a form. The form has a box for the dish, a box for the size, a box for extra toppings, and a box for the delivery address. Each box is filled separately, and the order is only placed when the form is handed over. The builder is that form. Each method call fills one box, and .body() hands the form over.

The Smallest Working Version

The smallest use of the builder is a GET request to the home route. A GET request asks for a resource without sending a body, so the body is empty.

tests/request_builder_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn builder_defaults_to_get() {
    let response = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

The Cargo.toml file is the same project file as the ServiceExt page, with tower as a dev-dependency and the util feature turned on.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5.3", features = ["util"] }

Run it with cargo test, and it passes:

test builder_defaults_to_get ... ok

Three calls build the request. Request::builder() creates an empty builder. .uri("/") sets the path. .body(Body::empty()) finishes the builder and returns the request. The method is GET even though no method was set, because GET is the builder default. The .unwrap() opens the Result that .body() returns, because building a request can fail.

Working Setup:

If cargo test prints ok for this test, the builder is working: the default method is GET, the URI is set, and an empty body completes the request.

Understanding the Builder Call by Call

The builder comes from the http crate, and Axum re-exports it as axum::http::Request, so the test imports it from axum::http. The type is http::request::Builder, and each of its methods returns the builder again, which is what lets the calls chain together. The chain ends with .body(), which is the only method that produces a Request. Everything before it is setup, and everything after it is the request itself.

The method

Request::builder()
    .method(Method::POST)

.method() sets the HTTP method, the verb that says what the request wants to do. Method::POST is the constant for POST, and the http crate provides constants for the rest: Method::GET, Method::PUT, Method::DELETE, Method::PATCH. The method can also be given as a string, .method("POST"), which parses the text into a Method and fails at runtime if the text is not a valid method. The constant form is the better default, because a typo in a constant fails at compile time while a typo in a string fails when the test runs.

If .method() is never called, the method is GET. That default is why the smallest example works with only a URI and a body. It is also why a test that forgets to set POST on a create request gets a 405 instead of a 201. The route exists, the method does not match, and the builder quietly sent a GET.

The URI

Request::builder()
    .uri("/books/1")

.uri() sets the path the request targets, and it accepts a string or any value that can become a URI. The path can carry a query string, the part after the ? that holds key-value pairs, as in /books?title=Dune. The builder validates the URI when .body() runs, and an invalid URI makes .body() return an Err instead of a request. The URI does not need a scheme or a host in a test, because there is no network and no server to address. A plain path is enough, and the router matches on the path alone.

The headers

Request::builder()
    .header("content-type", "application/json")

.header() adds one header, a name-value pair that travels with the request. The name is case-insensitive, so content-type and Content-Type mean the same thing, and the value must be valid header text. Each call adds one header, and calling it twice with the same name adds a second value rather than replacing the first. Headers carry the metadata the handler needs: what format the body is in, who the caller claims to be, and what the caller accepts back. The admin route in the book app reads x-token and x-role headers, and the create route needs the content type header to accept its JSON body.

The body

.body(Body::empty())

.body() is the call that finishes the builder. It takes the body value, validates everything collected so far, and returns Result<Request, http::Error>. The Result is why the test calls .unwrap() after it. A body is always required, even for a GET, because the builder cannot produce a request without one. Body::empty() is the body with nothing in it, and it is the right body for requests that send no data.

The body type is axum::body::Body, and Body::from builds one from a value. A string literal, a String, a byte vector, and a byte slice all work, and each form appears in the richer example below. The body is a stream of bytes, which means the handler reads it piece by piece rather than receiving it all at once, but in a test the whole body is written in one call and read in one go.

The Concept Behind the Builder Pattern

A request has four parts that are independent of each other, and a builder lets each part be set on its own line. The alternative would be a single function that takes all four parts at once, which would force every test to supply every part even when most of them are defaults. The builder keeps the common case short, a URI and an empty body, and the unusual case explicit, a method and headers added only when the test needs them.

The builder also validates at the end, not at each step. Setting an invalid URI does not fail when .uri() runs. It fails when .body() runs, because that is the moment the builder has everything it needs to check the whole request. That is why the error surfaces as a Result from .body() and not from the individual setter calls. The design trades early errors for a simpler chain, and the .unwrap() at the end is where the test pays for it.

Why the Request Must Be Built, Not Written

A test could build a request by writing raw HTTP text, the way a client sends bytes over a socket, but that text would need exact formatting, correct line endings, and a correct content length. The builder removes all of that. The test states what the request means, and the builder produces a well-formed request value. The router never sees text. It sees the value, with the method, URI, headers, and body already parsed and separated. A malformed request in a test is almost always a bug in the test, not a behaviour worth checking, so the builder failing loudly on invalid input is a feature.

A Richer Complete Example

The smallest version sent a bare GET. A realistic test file builds many kinds of requests, and each test below exercises one piece of the builder. The file covers the default GET, a POST with a JSON body, a query string, request headers, the string form of the method, the string and byte forms of the body, and the invalid URI error.

tests/request_builder_test.rs
use axum::{
    body::Body,
    http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn body_text(response: axum::response::Response) -> String {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

#[tokio::test]
async fn builder_defaults_to_get() {
    let response = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn builder_sets_the_method_and_uri() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    assert_eq!(
        body_text(response).await,
        r#"{"id":2,"title":"Dune"}"#
    );
}

#[tokio::test]
async fn builder_carries_a_query_string_in_the_uri() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books?title=Dune")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        body_text(response).await,
        r#"[{"id":2,"title":"Dune"}]"#
    );
}

#[tokio::test]
async fn builder_sets_request_headers() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/admin")
                .header("x-token", "secret-token")
                .header("x-role", "admin")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(body_text(response).await, r#"{"role":"admin"}"#);
}

#[tokio::test]
async fn builder_method_from_a_string() {
    let response = app()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn builder_rejects_an_invalid_uri() {
    let result = Request::builder().uri("http://[::1").body(Body::empty());
    assert!(result.is_err());
}

#[tokio::test]
async fn body_from_a_string_sends_text() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(String::from(r#"{"title":"Dune"}"#)))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn body_from_bytes_sends_the_same_json() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(br#"{"title":"Dune"}"#.to_vec()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn json_body_without_a_content_type_header_is_rejected() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
}

Run it with cargo test, and all nine tests pass:

test body_from_a_string_sends_text ... ok
test body_from_bytes_sends_the_same_json ... ok
test builder_carries_a_query_string_in_the_uri ... ok
test builder_defaults_to_get ... ok
test builder_method_from_a_string ... ok
test builder_rejects_an_invalid_uri ... ok
test builder_sets_request_headers ... ok
test builder_sets_the_method_and_uri ... ok
test json_body_without_a_content_type_header_is_rejected ... ok

The query string test shows the URI carrying data to the handler. The list route reads the title query parameter and keeps only the book whose title contains it, so the response holds one book instead of two. The headers test shows the admin route reading x-token and x-role from the request. Without both headers, the same request gets 401 or 403, and the status assertion page checks those cases. The invalid URI test shows the builder failing without a panic. It binds the Result from .body() and asserts it is an error, which is the correct way to test a builder failure. The last test shows what happens when the content type header is missing. The JSON body is present and well formed, but the Json extractor refuses it with 415, because the extractor trusts the header, not the bytes.

The Header and the Body Travel Together:

A JSON body without a content-type: application/json header is rejected with 415 before the handler runs, even when the bytes are valid JSON. The extractor reads the header to decide how to parse the body, and no header means no parse. Every POST test that sends JSON needs both lines, the header and the body.

Setting the Method

The method is the first decision in a request, and the builder default makes it easy to forget. A test for the create route that omits .method(Method::POST) sends a GET to /books, and the list handler answers 200 with the book list instead of the create handler answering 201. The test then fails on the status, and the failure looks like the create handler is broken when the real fault is the missing method call. The fix is to set the method explicitly in every test that is not a GET, and to read the method line first when a test returns an unexpected status.

The string form, .method("POST"), parses the text at runtime. It is useful when the method comes from a variable, such as a table of cases, and it panics on invalid input. The constant form, .method(Method::POST), is checked at compile time and is the better default for tests that hardcode the method.

Carrying Data in the URI

The URI carries the path and, after the ?, the query string. The query string holds key-value pairs separated by &, and the handler reads them with the Query extractor. The test writes the query string as part of the URI, in plain text, with no separate builder call. A value with a space or a special character must be percent-encoded, which means the space becomes %20 and the & becomes %26, because a raw space in a URI is invalid and the builder rejects it. The list route test uses title=Dune, which needs no encoding, and that is the common case.

Setting Headers

Headers are set one per .header() call, and the name is case-insensitive. The value must be valid header text, which means printable characters without newlines. A value built from user input that contains a newline fails at the .header() call, and the builder returns an error from .body() at the end. Headers are how a test pretends to be an authenticated client, an admin client, or a client that accepts a particular format. The admin tests set x-token and x-role to pass the header checks in the handler, and a test that omits them checks the rejection path instead. Both directions matter, and the builder makes each one a single line.

Choosing the Body Form

Body::empty() is the body for requests that send nothing, which is every GET and every DELETE in this app. Body::from builds a body from a value, and the value decides the form. A string literal is the shortest form for JSON, and the raw string syntax r#"..."# keeps the JSON quotes readable. A String works the same way and is the form to use when the body is built at runtime, such as a JSON string assembled with format!. A byte vector, br#"..."#.to_vec(), is the form for bytes that are not valid text, such as an image upload, and it proves the body is bytes first and text second.

The three forms produce the same body for the same bytes, and the handler cannot tell which form the test used. The choice is about the test code, not about the request. Use the literal for fixed JSON, the String for built JSON, and the byte vector for non-text data.

What Makes a Request Invalid

The builder validates the URI and the header values when .body() runs, and an invalid one makes .body() return an Err. The test for an invalid URI uses "http://[::1", a URI with an unclosed bracket, and asserts the result is an error. The request is never built, so it is never sent, and the test proves the builder guards its input. A test that unwraps the result instead would panic, which is also a signal, but asserting is_err() states the expectation plainly and keeps the test green.

The common invalid inputs are a URI with a space in it, a URI with an unclosed bracket, and a header value with a newline. All three come from building request data with format! and not encoding the result. The fix is to encode the value before putting it in the URI or the header, or to build the request from known-good literals, which is what every other test in the file does.

How a Built Request Travels

The diagram below follows a request from the builder to the handler.

Request::builder() creates an empty builder
        |
        v
.method() sets the verb, GET by default
        |
        v
.uri() sets the path and query string
        |
        v
.header() adds one name-value pair per call
        |
        v
.body() validates everything and returns the Request
        |
        v
oneshot sends the Request through the Router
        |
        v
Router matches the route and runs the handler

The builder owns the first five steps, and the router owns the last two. The split is clean. The builder decides what the request says, and the router decides what the request means.

Testing the Builder Itself

The test file in the richer example is the testing section for this page. It covers the builder from eight angles: the default method, an explicit method and URI, a query string, headers, the string form of the method, the string and byte forms of the body, and the invalid URI error, plus the missing content type rejection. All nine tests passed against the scratch project with axum 0.8.9, tower 0.5.3, and tokio 1.54.1. Run them with cargo test --test request_builder_test to run just this file, or cargo test to run the whole suite.

Common Beginner Mistakes

Forgetting to call body

// Wrong - the builder is not a Request
let request = Request::builder().uri("/books/1");
let response = app().oneshot(request).await.unwrap();

The builder is not a request, and oneshot expects a Request, so this fails to compile. The fix is .body(Body::empty()) at the end of the chain, which produces the request.

The Chain Is Not Finished Until body Runs:

Every builder chain must end with .body(). The method, URI, and header calls only collect parts. Without the final call there is no request, and the compiler stops the test before it runs.

Calling a setter after body

// Wrong - body consumes the builder, so nothing can follow it
let request = Request::builder()
    .uri("/books/1")
    .body(Body::empty())
    .unwrap()
    .header("x-token", "secret-token");

.body() consumes the builder and returns a Request, and a Request has no .header() builder method. The fix is to set every header before .body(), while the value is still a builder.

Forgetting the method on a POST

// Wrong - this sends a GET, and the list handler answers 200
let response = app()
    .oneshot(
        Request::builder()
            .uri("/books")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"title":"Dune"}"#))
            .unwrap(),
    )
    .await
    .unwrap();

The route /books exists for both GET and POST, so the request reaches the list handler instead of the create handler and returns 200. The fix is .method(Method::POST) before the URI. When a test returns a status from the wrong handler, the method line is the first place to look.

Unwrapping a builder error instead of asserting it

// Wrong - the test panics instead of stating the expectation
let request = Request::builder().uri("http://[::1").body(Body::empty()).unwrap();

The URI is invalid, so .body() returns an Err and the unwrap panics. The test fails, but it fails with a panic message instead of a clear assertion. The fix is to bind the result and assert is_err(), as the invalid URI test does.

Sending JSON without the content type header

// Wrong - the Json extractor rejects the body with 415
let response = app()
    .oneshot(
        Request::builder()
            .method(Method::POST)
            .uri("/books")
            .body(Body::from(r#"{"title":"Dune"}"#))
            .unwrap(),
    )
    .await
    .unwrap();

The body is valid JSON, but the extractor never reads it, because the header that marks it as JSON is missing. The response is 415 Unsupported Media Type. The fix is .header("content-type", "application/json") before the body.

Final Complete Example

Here is everything from this page in one place: the test file with all nine tests and the body helper, and the command to run them.

tests/request_builder_test.rs
use axum::{
    body::Body,
    http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn body_text(response: axum::response::Response) -> String {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

#[tokio::test]
async fn builder_defaults_to_get() {
    let response = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn builder_sets_the_method_and_uri() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    assert_eq!(
        body_text(response).await,
        r#"{"id":2,"title":"Dune"}"#
    );
}

#[tokio::test]
async fn builder_carries_a_query_string_in_the_uri() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books?title=Dune")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        body_text(response).await,
        r#"[{"id":2,"title":"Dune"}]"#
    );
}

#[tokio::test]
async fn builder_sets_request_headers() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/admin")
                .header("x-token", "secret-token")
                .header("x-role", "admin")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(body_text(response).await, r#"{"role":"admin"}"#);
}

#[tokio::test]
async fn builder_method_from_a_string() {
    let response = app()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn builder_rejects_an_invalid_uri() {
    let result = Request::builder().uri("http://[::1").body(Body::empty());
    assert!(result.is_err());
}

#[tokio::test]
async fn body_from_a_string_sends_text() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(String::from(r#"{"title":"Dune"}"#)))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn body_from_bytes_sends_the_same_json() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(br#"{"title":"Dune"}"#.to_vec()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn json_body_without_a_content_type_header_is_rejected() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
}

Run the file with:

cargo test --test request_builder_test

All nine tests pass, and every request in the file was built with the same four calls.

Summary

The builder is the vocabulary of the test request. Four calls cover everything a test needs to say: the method names the action, the URI names the target, the headers carry the metadata, and the body carries the data. The defaults keep the common case to two lines, and the explicit calls make the unusual case readable line by line. The habits that keep builder tests honest are small: set the method on every non-GET request, pair every JSON body with its content type header, and assert builder failures with is_err() instead of unwrapping them. With those habits, the request a test sends is exactly the request it meant to send, and a failing assertion points at the app, not at the test that built the request wrong.