String Body Extractor

Learn how to read raw UTF-8 request bodies as Strings in Axum handlers, including limits, errors, and complete working examples.

When a client sends data to your web server, that data lives inside the request body. The String body extractor is Axum's simplest tool for reading the entire body as a plain text String. It gives you the raw bytes interpreted as UTF-8 text, without any JSON parsing, form decoding, or other transformation.

This matters because many real APIs send plain text. A webhook might POST a CSV file. A monitoring agent might send a log line. A client might upload a .txt file. In all these cases, you want the text exactly as it was sent, not wrapped in a JSON structure. The String extractor is the direct route to that raw text.

A First Working Example

Before we look at every detail, here is the smallest complete Axum application that reads a request body as a String. Create a new Rust project, add Axum to Cargo.toml, then replace main.rs with this code.

# Cargo.toml
[package]
name = "string-body-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
// main.rs
use axum::{routing::post, Router};
async fn echo_string(body: String) -> String {
    body
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/echo", post(echo_string));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The handler echo_string declares one parameter: body: String. Axum sees that parameter and knows it must read the entire request body, interpret the bytes as UTF-8, and pass the resulting String into the handler. The handler then returns that same String, which Axum sends back as the response body.

Run the server with cargo run, then test it from a second terminal:

curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: text/plain" \
  -d "Hello from the request body"

The response contains exactly the text you sent. That is the whole flow: client sends a string, handler receives a string, handler returns a string.

What the String Extractor Actually Does

Axum calls String a body-consuming extractor. That phrase means the extractor reads the request body and consumes it. Once the body has been read into a String, it cannot be read again by another extractor in the same handler.

When you write async fn handler(body: String), Axum performs these steps before calling your handler:

  1. It buffers the raw bytes of the request body into memory.
  2. It checks whether those bytes are valid UTF-8.
  3. If the bytes are valid, it creates a String from them and passes it to your handler.
  4. If the bytes are not valid UTF-8, Axum rejects the request and returns an error response before your handler ever runs.

The important word here is buffers. Axum does not stream the body to you in chunks. It collects the whole body first, then hands you a complete String. This is convenient because your handler code treats the body as an ordinary variable, but it also means the entire body must fit in memory at once. For very large uploads, the Bytes extractor or streaming approaches may be better choices.

UTF-8 is the default text encoding:

UTF-8 is the standard way computers store text as bytes. Nearly all modern clients send text as UTF-8, so String works for the vast majority of text-based requests. If a client sends bytes that are not valid UTF-8, the String extractor rejects the request with a 400 Bad Request response.

The Body Limit and Why It Exists

Axum applies a default body limit to every request. The limit is 2 megabytes, or 2 * 1024 * 1024 bytes. If a client sends a body larger than that, Axum rejects the request before your handler runs.

This limit protects your server. Without it, a malicious client could send an enormous body and exhaust your server's memory. The limit is not specific to String - it applies to all body-consuming extractors, including Bytes and Json.

You can change the limit with the DefaultBodyLimit layer. Here is a server that allows up to 10 megabytes:

// main.rs
use axum::{
    extract::DefaultBodyLimit,
    routing::post,
    Router,
};
async fn echo_string(body: String) -> String {
    body
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo_string))
        .layer(DefaultBodyLimit::max(10 * 1024 * 1024));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The DefaultBodyLimit::max(10 * 1024 * 1024) call sets the limit to 10 megabytes for all routes in this router. You can also disable the limit entirely with DefaultBodyLimit::disable(), but that is rarely a good idea in production.

Body limit rejections are not String-specific errors:

If a request body exceeds the limit, Axum rejects the request with a 413 Payload Too Large response. Your handler does not run. This behavior is identical for String, Bytes, and Json extractors. The limit is applied by the extractor itself when it buffers the body (using the DefaultBodyLimit value from the request extensions, which defaults to 2,097,152 bytes); there is no default limit layer on the router.

Which Content Types Work with String

One common beginner surprise is that String does not check the Content-Type header. You can send a body with Content-Type: application/json, Content-Type: text/plain, or even no Content-Type header at all, and the String extractor will still read the body and hand you the raw text.

This is different from the Json extractor, which requires the Content-Type: application/json header and rejects requests that do not have it. String is more permissive because it does not promise anything about the body's format. It just gives you the bytes as text, whatever those bytes are.

Here is the same server tested with multiple content types:

# Works fine - String does not require text/plain
curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: application/json" \
  -d '{"message": "this is JSON text"}'
# Also works - no Content-Type header at all
curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type:" \
  --data-binary "No content type sent"
# Works - form data is just text
curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "name=alice&age=30"

In every case, the handler receives exactly what you sent. That is the core promise of String: no filtering, no format enforcement, no transformation.

The Error Path and How to Handle It

The String extractor has a rejection type: StringRejection. When extraction fails, Axum returns an error response and your handler never runs. To handle the failure inside your handler instead, wrap the extractor in Result.

The two failure cases are:

  • The body is not valid UTF-8. This produces StringRejection::InvalidUtf8.
  • The body could not be buffered. This produces StringRejection::FailedToBufferBody, which typically means the body exceeded the limit.

Here is a handler that catches both cases and returns a custom message instead of Axum's default response:

// main.rs
use axum::{
    extract::rejection::StringRejection,
    http::StatusCode,
    routing::post,
    Router,
};
async fn handle_body(result: Result<String, StringRejection>) -> (StatusCode, String) {
    match result {
        Ok(body) => {
            let message = format!("Received body with {} bytes", body.len());
            (StatusCode::OK, message)
        }
        Err(StringRejection::InvalidUtf8(_)) => {
            (StatusCode::BAD_REQUEST, "Body is not valid UTF-8".to_string())
        }
        Err(StringRejection::FailedToBufferBody(_)) => {
            (
                StatusCode::PAYLOAD_TOO_LARGE,
                "Body is too large".to_string(),
            )
        }
        Err(_) => (StatusCode::BAD_REQUEST, "Unknown body error".to_string()),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/body", post(handle_body));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

When you send valid text, the handler reports how many bytes the body contained. When you send invalid UTF-8, you get your custom 400 message. When you send a body larger than 2 MB, you get your custom 413 message.

UTF-8 validation happens silently unless you handle the rejection:

If you do not wrap String in Result, an invalid UTF-8 body causes Axum to return a default error response and your handler is skipped entirely. Beginners often send binary data to a String endpoint and wonder why their handler never runs. Always consider whether your endpoint might receive non-text data.

Common Beginner Mistakes with String Body Extraction

The String extractor is simple, but a handful of mistakes show up repeatedly in real projects.

Mistake 1: Using String to Parse JSON

If your client sends JSON, use the Json extractor. The String extractor gives you raw JSON text, and you would need to parse it manually with serde_json. That manual path works but adds boilerplate and loses Axum's automatic rejection handling for malformed JSON.

// Not recommended: manually parsing JSON from a String body
use axum::{routing::post, Router};
use serde_json::Value;
async fn create_user(body: String) -> String {
    match serde_json::from_str::<Value>(&body) {
        Ok(value) => format!("Parsed JSON: {}", value),
        Err(err) => format!("Invalid JSON: {}", err),
    }
}

This works, but you are now responsible for every JSON error case. The Json extractor handles those errors for you. This fragment also needs serde_json = "1" in Cargo.toml, since the page's example project does not include it yet.

Mistake 2: Expecting String to Reject Wrong Content Types

Some beginners assume String only accepts text/plain. That is not the case. String accepts any body regardless of content type. If your endpoint must reject non-text content types, you need to check the Content-Type header yourself using a header extractor alongside String.

Mistake 3: Using String for Binary Data

If the client might send arbitrary binary data - images, PDFs, compressed files - use the Bytes extractor. Bytes gives you raw bytes without UTF-8 validation. String will reject binary data that is not valid UTF-8.

When String is exactly right:

Use String when you know the client sends human-readable text: plain text messages, CSV data, log lines, source code, or any text-based format that does not need structured parsing. For binary data, Bytes is the safer choice. For structured formats, Json or Form is better.

Reading a CSV File Sent as Plain Text

A practical example that shows String in a realistic role: a client uploads a CSV file, and the server parses the text into rows.

// main.rs
use axum::{routing::post, Router};
async fn parse_csv(body: String) -> String {
    let mut output = String::new();
    for line in body.lines() {
        let fields: Vec<&str> = line.split(',').collect();
        output.push_str(&format!("Row with {} fields: {:?}\n", fields.len(), fields));
    }
    output
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/csv", post(parse_csv));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Test it with a small CSV payload:

curl -X POST http://127.0.0.1:3000/csv \
  -H "Content-Type: text/csv" \
  -d $'name,age,city\nalice,30,berlin\nbob,25,paris'

The handler iterates over each line, splits on commas, and reports how many fields each row contains. The String extractor gives you the whole file as one String; the .lines() method then splits it cleanly at newline boundaries.

Combining String with a Path Parameter

String works alongside extractors that read from the URL path. Since String consumes the body, it must appear last in the handler parameter list. Axum enforces this at compile time.

// main.rs
use axum::{extract::Path, routing::post, Router};
async fn upload_note(Path(file_name): Path<String>, body: String) -> String {
    format!("Stored {} with {} characters", file_name, body.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/notes/{file_name}", post(upload_note));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

A request to /notes/meeting.txt with a body of "Discuss roadmap" returns Stored meeting.txt with 15 characters. The path parameter comes from the URL, the String comes from the body, and both arrive as ordinary Rust variables in the handler.

Why the Body Can Only Be Read Once

Every Axum request body is an asynchronous stream of bytes. A stream is like a pipe: data flows through it once, in order. You cannot rewind a stream and read it again.

Axum encodes this rule in its type system. String implements FromRequest, which consumes the request body. Every other extractor in the same handler must implement FromRequestParts, which reads from the request's metadata - path, query, headers - but not the body. Axum's compiler checks ensure you never put two body-consuming extractors in the same handler.

// This does not compile: two body-consuming extractors
use axum::{body::Bytes, routing::post, Router}; // String needs no import: it is std's String, already in the prelude
async fn broken_handler(body: String, bytes: Bytes) {
    let _ = (body, bytes);
}
#[tokio::main]
async fn main() {
    // Error: both extractors try to consume the body, so `broken_handler`
    // does not implement `Handler` and this line fails to compile.
    let _app = Router::new().route("/broken", post(broken_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, _app).await.unwrap();
}

The fix is to choose one body extractor and use it for everything you need. If you want the raw bytes, use Bytes. If you want the text, use String. You cannot have both in the same handler.

String vs Bytes vs Json in Practice

Three common extractors read the request body: String, Bytes, and Json. They differ in what they validate and what they return.

  • String validates UTF-8 and returns a String. Best for plain text, CSV, logs, and any text-based raw format.
  • Bytes does no validation and returns raw bytes. Best for binary data or when you need maximum control.
  • Json validates both UTF-8 and JSON structure, then deserializes into a typed struct. Best for structured data like API payloads.

The following table summarizes the trade-offs:

ExtractorValidates UTF-8Validates JSONReturnsUse when
StringYesNoStringClient sends plain text
BytesNoNoBytesClient sends binary data
Json<T>YesYesTClient sends structured JSON

For this page, the takeaway is that String sits between the other two: it refuses binary data by checking UTF-8, but it does not attempt to parse any particular text format.

How Beginners Should Think About the String Extractor

A good mental model is a mailbox. When a client sends a request, the body is a package placed in your mailbox. The String extractor opens the package, checks that the contents are text (UTF-8), and hands you the text. If the package contains something that is not text - a photo, a compressed archive, random binary - the mailbox refuses delivery and returns the package to the sender with a 400 error.

This mental model helps explain the extractor's behavior. It does not care what the text means. It does not parse JSON or CSV or XML. It only verifies that the bytes are valid text, then hands them over.

The word 'extractor' means data from the request:

In Axum terminology, an extractor is a type that pulls data out of an incoming HTTP request. Path extracts from the URL path. Query extracts from query parameters. String extracts from the body. All extractors share the same core idea: the handler declares what it needs, and Axum fetches it before running the handler code.

Using String with a Content-Type Check

Sometimes you want the convenience of String but also want to ensure the client sent the right content type. You can combine String with a header extractor to add that check manually.

// main.rs
use axum::{
    http::{header::CONTENT_TYPE, HeaderMap, StatusCode},
    routing::post,
    Router,
};
async fn text_only(headers: HeaderMap, body: String) -> Result<String, (StatusCode, &'static str)> {
    let content_type = headers
        .get(CONTENT_TYPE)
        .and_then(|value| value.to_str().ok());
    match content_type {
        Some("text/plain") | Some("text/plain; charset=utf-8") => Ok(body),
        Some(other) => Err((
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "Only text/plain is accepted",
        )),
        None => Err((StatusCode::BAD_REQUEST, "Missing Content-Type header")),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/text", post(text_only));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Here the HeaderMap extractor reads request headers without touching the body. The String extractor still appears last, since it consumes the body. The handler manually checks the Content-Type and returns a 415 Unsupported Media Type error if the client sends anything other than text/plain.

Handling Very Large Text Bodies

The default 2 MB limit is enough for many cases, but some workloads need more. A log ingestion endpoint, for example, might receive single files that are 10 MB or larger. The DefaultBodyLimit layer adjusts the limit globally for a router.

// main.rs
use axum::{
    extract::DefaultBodyLimit,
    routing::post,
    Router,
};
async fn ingest_log(body: String) -> String {
    format!("Ingested {} lines", body.lines().count())
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/logs", post(ingest_log))
        .layer(DefaultBodyLimit::max(50 * 1024 * 1024)); // 50 MB
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running at http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This server accepts bodies up to 50 MB on the /logs route and counts lines in the uploaded text. The handler itself stays simple; the limit change lives in the router configuration.

Larger limits mean larger memory usage:

Since String buffers the entire body in memory, a 50 MB limit means a single request can allocate 50 MB of memory on your server. If many large requests arrive at once, memory usage multiplies quickly. Set the limit only as high as your actual workloads require.

What Happens When UTF-8 Validation Fails

UTF-8 is a specific way of encoding characters into bytes. Most text follows this encoding, but not all byte sequences are valid UTF-8. When a client sends invalid UTF-8, the String extractor must reject the request because Rust's String type is guaranteed to be valid UTF-8.

You can test this with a small binary payload:

# Send bytes that are not valid UTF-8
printf '\xFF\xFE\x00' | curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: text/plain" \
  --data-binary @-

Using the first example server, this request produces a 400 Bad Request response because 0xFF 0xFE 0x00 is not valid UTF-8. The handler never runs.

If you wrap the extractor in Result, you can catch this failure and return a custom response. The StringRejection::InvalidUtf8 variant identifies exactly this case.

Summary and Decision Guidance

The String body extractor is the simplest way to read raw text from a request body in Axum. It validates UTF-8, buffers the body in memory, and hands the handler a complete String. It does not inspect the Content-Type header and does not parse any text format.

Reach for String when your endpoint receives plain text, CSV data, log entries, source code, or any other human-readable format that does not need structured parsing. When the client sends binary data, switch to Bytes. When the client sends structured JSON, use Json. The choice comes down to what you know about the incoming data format and what validation you need Axum to perform on your behalf.

If you find yourself needing the body as text but also needing to know more about the raw request - headers, method, URI - the Request extractor gives you the entire HTTP request object, from which you can access both the body and all request metadata.