Bytes Body Extractor in Axum - Reading Raw Request Body
Learn how to use the Bytes extractor in Axum to read the raw request body as binary data without JSON or text parsing.
When a client sends data to your server, that data lives in the request body. Sometimes the data is JSON, sometimes it's form fields, and sometimes it's something else entirely - an image, a compressed file, or just a stream of raw bytes. The Bytes extractor in Axum lets you grab that raw payload exactly as it arrived, without any parsing or validation. This page teaches you how to use it, why you'd want it, and what mistakes to avoid.
What Is a Request Body?
Every HTTP request has three main parts: the method (like GET or POST), the URL, and the body. The body is the chunk of data that comes after the headers. In a GET request, the body is usually empty. In a POST or PUT request, the body often carries the important data: a JSON object, an image, a file, or some other payload.
When you write an Axum handler, you usually want to access that body and do something with it. Axum provides extractors - special types that, when placed as function arguments, pull data out of the request for you. For example, Json<T> extracts and parses JSON into a Rust struct. String extracts the body as a UTF-8 string. The Bytes extractor does something different: it gives you the raw bytes, untouched.
Why Use Raw Bytes Instead of JSON or Text?
Most tutorials focus on JSON because it's common for APIs. But JSON is just one possible format. If you try to parse a PNG image as JSON, it fails. If you try to read a binary file as a String, you'll get an error unless the bytes happen to form valid UTF-8. Raw bytes are the lowest common denominator - they work for anything.
Here are situations where Bytes is the right tool:
- File uploads: receiving an image, PDF, or any binary file.
- Webhook signatures: verifying a payload by hashing the exact bytes sent by a third party.
- Custom protocols: you want to parse the body yourself using a binary format like CBOR or MessagePack.
- Debugging: you're not sure what format a client is sending and you want to inspect the raw data first.
The key idea: Bytes does not try to interpret the data. It just hands you a container with the exact bytes that arrived.
Bytes Is Raw and Unvalidated:
The Bytes extractor will accept any body regardless of its Content-Type header. You don't need to set application/json or text/plain. If the client sends a body, you'll get it. If the client sends an empty body, you'll get an empty Bytes.
The Bytes Type in Axum
When you write bytes: Bytes as a handler argument, what exactly is Bytes? It comes from the axum::body module and is actually a re-export of the Bytes type from the popular bytes crate. If you're new to Rust, you can think of Bytes as an immutable, cheaply cloneable sequence of raw bytes, similar to a &[u8] you own. Unlike Vec<u8> it is not growable (the growable counterpart is BytesMut); its strength is that cloning it shares the underlying buffer through reference counting instead of copying the data. For this page, you don't need to know the internals; just know that Bytes represents a sequence of raw bytes.
To use it, you must import axum::body::Bytes:
use axum::body::Bytes;
Your First Bytes Extractor - Minimal Example
Let's build the smallest possible server that reads a raw body and sends back its length. This will show the complete setup from start to finish.
Create a new Rust project (if you don't have one, run cargo new bytes-demo). Then edit Cargo.toml to include the dependencies:
[package]
name = "bytes-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Now open src/main.rs and replace everything with this:
use axum::{
body::Bytes,
routing::post,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/raw", post(raw_handler));
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();
}
async fn raw_handler(bytes: Bytes) -> String {
let length = bytes.len();
format!("Received {} bytes", length)
}
This code defines a single POST endpoint at /raw. The handler raw_handler takes one argument, Bytes, and Axum will automatically extract the request body into it. Inside the handler we call bytes.len() to get the number of bytes and return a simple string response.
The order of arguments matters: if a handler takes multiple extractors, any extractor that consumes the body (like Bytes, String, or Json) must be the last argument.
Running and Testing the Server
Start the server with cargo run. Then open a second terminal and use curl to send a POST request with some data. The -d flag sends the string after it as the request body:
curl -X POST -d "hello world" http://127.0.0.1:3000/raw
You should see the response:
Received 11 bytes
The string "hello world" contains 11 characters, each one byte in UTF-8, so the length is 11.
Now try sending an empty body:
curl -X POST -d "" http://127.0.0.1:3000/raw
The output is:
Received 0 bytes
That confirms that Bytes gives you whatever the client sent, even nothing.
Working Correctly:
If you see "Received 11 bytes" after the first request and "Received 0 bytes" after the second, your server is set up correctly and the Bytes extractor is doing its job.
Working with the Bytes Data
Now that you can receive raw bytes, let's explore what you can do with them. The Bytes type has many useful methods similar to Vec<u8>.
Getting the Length and Checking Emptiness
async fn raw_handler(bytes: Bytes) -> String {
if bytes.is_empty() {
return "No body provided".to_string();
}
format!("Body length: {} bytes", bytes.len())
}
Converting to a Vec<u8>
If you need a plain owned array of bytes (for example, to pass to a function that expects &[u8] or Vec<u8>), you can convert:
async fn raw_handler(bytes: Bytes) -> String {
let vec: Vec<u8> = bytes.to_vec();
// do something with vec, like using a hashing library
let first_byte = vec.first().copied().unwrap_or(0);
format!("First byte: {}", first_byte)
}
Slicing and Inspecting Bytes
You can slice Bytes just like a slice of an array:
async fn raw_handler(bytes: Bytes) -> String {
if bytes.len() < 4 {
return "Too short".to_string();
}
let first_four = &bytes[..4];
format!("First four bytes: {:?}", first_four)
}
When you print &[u8] with the {:?} formatter, it shows decimal values, not characters. So sending "ABCD" would give:
First four bytes: [65, 66, 67, 68]
Because ASCII 'A' is 65, 'B' is 66, and so on.
Converting to String When It's Valid UTF-8
If you believe the raw bytes represent text (like a plain text body sent without a proper content type), you can attempt to convert them to a String:
async fn raw_handler(bytes: Bytes) -> String {
match String::from_utf8(bytes.to_vec()) {
Ok(text) => format!("Received text: {}", text),
Err(_) => "Body was not valid UTF-8".to_string(),
}
}
This attempts to interpret the bytes as UTF-8. If any byte sequence is invalid (for example, a binary file), the conversion fails and the Err arm runs.
Practical Example - Binary Upload Echo with Metadata
A common pattern is to receive binary data, inspect it, and return some information about it. This example creates a POST endpoint /upload that accepts any raw body, calculates its length, and returns the first 10 bytes as a hexadecimal string.
To return JSON, we'll use axum::Json as a response. That requires adding serde to the dependencies. Update your Cargo.toml:
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
Now replace src/main.rs with:
use axum::{
body::Bytes,
routing::post,
Json, Router,
};
use serde::Serialize;
#[derive(Serialize)]
struct UploadInfo {
total_bytes: usize,
first_10_hex: String,
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/upload", post(upload_handler));
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();
}
async fn upload_handler(bytes: Bytes) -> Json<UploadInfo> {
let total_bytes = bytes.len();
let first_10: Vec<u8> = bytes.iter().take(10).copied().collect();
let first_10_hex = first_10
.iter()
.map(|b| format!("{:02x}", b))
.collect::<Vec<_>>()
.join(" ");
Json(UploadInfo {
total_bytes,
first_10_hex,
})
}
The handler receives the raw bytes, counts them, and takes the first 10 bytes. It converts each byte to a two-digit hexadecimal representation (like 0a for newline, ff for 255) and joins them with spaces. The struct UploadInfo is serialized to JSON and returned.
Test it with curl:
curl -X POST --data-binary "@some_file.bin" http://127.0.0.1:3000/upload
Replace some_file.bin with any file on your computer. You'll get a JSON response like:
{"total_bytes":1234,"first_10_hex":"89 50 4e 47 0d 0a 1a 0a 00 00"}
This output shows the total size and the first few bytes in hex, which is exactly what you'd see if the file is a PNG image (PNG files start with the bytes 89 50 4e 47).
Using --data-binary:
When sending binary data with curl, use --data-binary instead of -d. The -d flag strips newline characters from the data, which would corrupt binary content. (-d does not URL-encode; that is what --data-urlencode is for.) --data-binary sends the exact bytes from the file.
Handling Large Bodies and Default Limits
Axum has a built-in safety limit on the size of the request body it will buffer. The default is 2 MB (2,097,152 bytes). If a client sends more than that, the request will be rejected before your handler is called, and the client will receive a 413 Payload Too Large error.
This limit exists to prevent a malicious or accidental huge upload from exhausting your server's memory. For many binary upload endpoints, you'll want to increase it. You can do that using the DefaultBodyLimit layer, but that's a separate topic. For now, just be aware that if you're testing with a large file and get a 413 error, the body limit is the likely cause.
Default 2 MB Limit:
The Bytes extractor will not handle bodies larger than the default limit unless you explicitly configure a higher limit. When building file upload features, always plan for this limit and set it appropriately.
Common Mistakes and How to Avoid Them
Beginners often trip over a few recurring issues when using Bytes.
Mistake 1: Trying to Use Multiple Body Extractors
Each HTTP request has exactly one body, and Axum allows only one extractor to consume it. If you write a handler like this:
async fn bad_handler(body1: Bytes, body2: String) {
// ...
}
You'll get a compile error. The reason is that the body is a stream that can only be read once. Axum enforces the rule that only the last argument can implement FromRequest (consume the body), and all earlier arguments must implement FromRequestParts (only read headers or other parts). Since both Bytes and String consume the body, this is invalid.
Mistake 2: Not Making Bytes the Last Argument
Even if you only have one body extractor, it must be the last argument. This handler is also invalid:
async fn wrong_order(bytes: Bytes, method: axum::http::Method) {
// ...
}
Method only reads the request parts, so it should come before the body extractor. The correct order is:
async fn correct_order(method: axum::http::Method, bytes: Bytes) {
// ...
}
Compiler Errors About FromRequest vs FromRequestParts:
If you see a cryptic compile error saying that a type doesn't implement FromRequestParts, check the order of your handler arguments. The body-consuming extractor (like Bytes) must be last.
Mistake 3: Assuming the Body Is Always Valid UTF-8
Bytes gives you raw bytes, not a String. If you want to treat the body as text, you must convert it yourself and handle the error case. Calling String::from_utf8 on arbitrary binary data will often fail. Always check the result.
Mistake 4: Forgetting That the Body Might Be Empty
A client could send a POST request with no body at all. Your handler will receive an empty Bytes with length 0. If your logic assumes a non-empty body (for example, slicing the first byte), you must check is_empty() first to avoid a panic.
Mistake 5: Trying to Reuse the Same Bytes After Moving It
Bytes is not Copy. When you pass it to a function or assign it to another variable, the original variable is moved unless you clone it. For example:
async fn handler(bytes: Bytes) -> String {
let len = bytes.len(); // fine
let moved = bytes; // bytes is moved here
// bytes.len(); // error: bytes no longer available
format!("Len: {}", len)
}
If you need to keep using the data after moving it, clone it first (let clone = bytes.clone();). Cloning Bytes is cheap because it shares the underlying buffer.
Why Not Just Use Vec<u8> Directly?
You might wonder why Axum uses Bytes instead of Vec<u8>. The main reason is efficiency: Bytes allows multiple parts of your code to share the same data without copying the entire buffer. When Axum reads the request body, it can store it in a Bytes and then hand you a clone that still points to the same memory. With Vec<u8>, cloning would require a full copy of every byte. For large bodies, that difference matters. For learning purposes, you can treat Bytes almost like a Vec<u8>; just remember it's a separate type with a few different methods.
A Complete Review of the Basics
Let's walk through one more complete example that combines several ideas: receiving raw bytes, checking the length, converting to text if possible, and returning a custom response. This will also show how to use axum::response::IntoResponse to return different types depending on the outcome.
use axum::{
body::Bytes,
http::StatusCode,
response::{IntoResponse, Response},
routing::post,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/inspect", post(inspect_handler));
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();
}
async fn inspect_handler(bytes: Bytes) -> Response {
if bytes.is_empty() {
return (StatusCode::BAD_REQUEST, "No body sent").into_response();
}
let length = bytes.len();
match String::from_utf8(bytes.to_vec()) {
Ok(text) => {
let response = format!("Got text of length {}: {}", length, text);
(StatusCode::OK, response).into_response()
}
Err(_) => {
let first_bytes: Vec<u8> = bytes.iter().take(5).copied().collect();
let response = format!(
"Got binary data of length {}. First 5 bytes: {:?}",
length, first_bytes
);
(StatusCode::OK, response).into_response()
}
}
}
This handler first checks for an empty body and returns a 400 error. Then it tries to interpret the body as UTF-8 text. If that succeeds, it returns the text. If not, it returns a message with the first five bytes as decimal numbers. This pattern is useful when you need to support both text and binary uploads in the same endpoint.
Test with a text body:
curl -X POST -d "hello" http://127.0.0.1:3000/inspect
Output:
Got text of length 5: hello
Test with binary data (e.g., a PNG file):
curl -X POST --data-binary "@image.png" http://127.0.0.1:3000/inspect
Output will be something like:
Got binary data of length 12345. First 5 bytes: [137, 80, 78, 71, 13]
Handling Both Text and Binary:
This pattern is a solid approach when you don't know in advance what kind of data clients will send. It lets you safely handle both cases without panicking.
The Relationship Between Bytes and Other Raw Extractors
This page is focused on Bytes, but you should know it's not the only raw extractor Axum offers. There is also a String extractor that attempts to convert the body to UTF-8 and rejects the request if it fails, and a Request extractor that gives you the entire request object, including headers, method, and body. Each has its use case. Bytes is the right choice when you need the exact raw bytes and want to handle text conversion or binary parsing yourself.
Summary
The Bytes extractor is the simplest way to read the raw HTTP request body in Axum. It doesn't parse, validate, or assume anything about the data - it just hands you the bytes exactly as they arrived. That makes it ideal for file uploads, custom binary protocols, webhook verification, and any situation where JSON or text parsing would be inappropriate.
You've learned how to write handlers that accept Bytes, how to inspect the data, how to convert it to other forms, and how to avoid the most common mistakes like using multiple body extractors or forgetting the 2 MB default limit. With this foundation, you can build endpoints that accept any kind of raw data and process it safely.
The natural next step is to explore the String extractor if you expect text bodies, or the Request extractor if you need full control over the request. Both build on the same concepts covered here - one body, consumed once, by the last argument in your handler.