Hyper as HTTP Library vs Axum
Compare the low-level Hyper HTTP library with the Axum web framework to understand what each provides and when to use one directly versus the other
Both Hyper and Axum appear in a typical Rust web stack, but they solve different layers of the same problem. Hyper implements the HTTP protocol itself. Axum gives you a comfortable API for building web services on top of that protocol. This page walks through what each one actually does, with complete code examples for both, so you can see exactly where Hyper stops and Axum begins.
The Problem They Both Touch
When a browser or mobile app sends a request to a Rust server, that request travels over a network socket. Some software on the server must read raw bytes from that socket, recognize them as an HTTP request, and figure out where the body starts and ends. That job belongs to Hyper.
Once the request has been parsed, another piece of software must decide which piece of your application logic should handle it. That decision - "the path is /users/42, so call the function that fetches user 42" - is routing. That job belongs to Axum.
Two Different Layers:
Hyper is an HTTP implementation. Axum is a web application framework. You can build a web server using only Hyper, and many people do. But you will write a lot of code that Axum would write for you.
What Hyper Actually Is
Hyper is a Rust crate that implements the HTTP/1.1 and HTTP/2 protocols. It knows how to receive a stream of bytes from a TCP connection, parse them into an HTTP request with a method, headers, and body, and then serialize an HTTP response back into bytes.
Hyper does not know what a "route" is. It does not know what a "handler" is in the Axum sense. It gives you a single entry point - a function that receives every request - and leaves it to you to inspect the request and decide what to do.
To use Hyper directly, you accept incoming TCP connections, hand each one to a Hyper connection handler, and provide a service function that processes every request. The http1::Builder::serve_connection used below is Hyper's low-level API - it serves one connection, and you write the accept loop around it. Most code does not use it directly: hyper-util's server::conn::auto::Builder serves a connection with automatic HTTP/1 + HTTP/2 negotiation (see below), and axum::serve wraps all of this for you.
Here is the smallest usable Hyper server:
// Cargo.toml
// [dependencies]
// hyper = { version = "1", features = ["server", "http1"] }
// tokio = { version = "1", features = ["full"] }
// hyper-util = { version = "0.1", features = ["tokio"] }
// http-body-util = "0.1"
use http_body_util::{BodyExt, Full};
use hyper::body::{Bytes, Incoming};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
type BoxBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;
fn full_body(text: &'static str) -> BoxBody {
Full::new(Bytes::from(text))
.map_err(|never| match never {})
.boxed()
}
async fn handle_request(_req: Request<Incoming>) -> Result<Response<BoxBody>, hyper::Error> {
Ok(Response::new(full_body("Hello from Hyper!")))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
loop {
let (stream, _addr) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(io, service_fn(handle_request))
.await
{
eprintln!("connection error: {err}");
}
});
}
}
There are several moving parts here. The TcpListener binds to port 3000 and waits for incoming connections. Each connection is wrapped in a TokioIo adapter so Hyper can read from it using Tokio's async primitives. The http1::Builder tells Hyper to speak HTTP/1.1 on that connection. And service_fn wraps your handle_request function so Hyper can call it as a service.
Notice that handle_request receives every request regardless of method or path. If you send GET /, it responds. If you send POST /anything, it responds with the same thing. If you send DELETE /does-not-exist, it still responds. Hyper has parsed the request for you - you could inspect _req to see the method, path, and headers - but it has not made any decisions about what should happen next. That decision is entirely yours to code.
The usual shortcut: hyper-util's auto::Builder
Hyper 1.x (current: 1.12.0) split its supporting code into a separate crate, hyper-util. The accept loop above is the manual form; the form most servers actually use is hyper_util::server::conn::auto::Builder, which negotiates HTTP/1 vs HTTP/2 for each connection automatically:
use hyper_util::{
rt::{TokioExecutor, TokioIo},
server::conn::auto,
};
// ... inside the accept loop, after `let io = TokioIo::new(stream);`:
tokio::spawn(async move {
if let Err(err) = auto::Builder::new(TokioExecutor::new())
.serve_connection(io, service_fn(handle_request))
.await
{
eprintln!("connection error: {err}");
}
});
auto::Builder replaces http1::Builder (and the separate http2::Builder) with one builder that picks the protocol per connection. And if even that is more control than you need, axum::serve is the next step up: it runs the same accept loop and the same auto builder internally, and hands each request to your Router instead of a hand-written service function.
What Axum Actually Is
Axum is a routing and request-handling library built on top of Hyper. It uses Hyper to speak HTTP, but adds a layer above it that maps paths and methods to your handler functions. When you use Axum, you never touch TcpListener, serve_connection, or service_fn directly. Axum handles the connection loop internally and calls only the handler that matches the request.
Here is the same basic server written in Axum:
// Cargo.toml
// [dependencies]
// axum = "0.8"
// tokio = { version = "1", features = ["full"] }
use axum::{routing::get, Router};
async fn handle_request() -> &'static str {
"Hello from Axum!"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handle_request));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The Axum version has no connection loop, no TokioIo, no BoxBody, and no service_fn. You declare a route - GET / goes to handle_request - and then hand the router to axum::serve, which takes care of everything else. The reduction in code is not just aesthetic; it eliminates entire categories of mistakes that happen when you manage connections manually.
The Trade-Off in Code Volume:
The Axum version is shorter because Axum runs that boilerplate for you at runtime, inside the framework. When you call axum::serve, the code that binds, accepts, and serves connections still runs - you just don't write it. This is the core value of a framework: taking repetitive infrastructure code and moving it into a reusable layer.
How Beginners Should Think About the Split
Imagine Hyper as a postal service that delivers envelopes to your desk. Every envelope arrives at the same place. Hyper has opened the envelope, checked the address, and laid out the contents - but it hands every envelope to the same person. That person is you, and you must sort through everything manually.
Axum adds a mailroom with a sorting machine on top. The postal service still delivers to the mailroom, but now a router reads the address and puts each envelope into a specific bin. Each bin corresponds to a handler function. You only handle what lands in your bin.
This mental model explains why the two crates have different failure modes. In Hyper, if you forget to inspect the request path, every request goes to the same handler and you might return wrong responses. In Axum, if a route is not declared, the router returns a 404 automatically - you don't have to write that fallback yourself.
Routing - The Biggest Difference
In a Hyper-only server, routing means reading the request's URI and method, then matching them with if statements or a match. The code becomes tedious quickly.
Here is a Hyper server that responds differently to three paths:
// Cargo.toml
// [dependencies]
// hyper = { version = "1", features = ["server", "http1"] }
// tokio = { version = "1", features = ["full"] }
// hyper-util = { version = "0.1", features = ["tokio"] }
// http-body-util = "0.1"
use http_body_util::{BodyExt, Full};
use hyper::body::{Bytes, Incoming};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
type BoxBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;
fn full_body(text: &'static str) -> BoxBody {
Full::new(Bytes::from(text))
.map_err(|never| match never {})
.boxed()
}
async fn handle_request(req: Request<Incoming>) -> Result<Response<BoxBody>, hyper::Error> {
let path = req.uri().path();
let method = req.method();
let response = if path == "/" && method == Method::GET {
Response::builder()
.status(StatusCode::OK)
.body(full_body("Welcome to the home page"))
.unwrap()
} else if path == "/about" && method == Method::GET {
Response::builder()
.status(StatusCode::OK)
.body(full_body("About this server"))
.unwrap()
} else if path == "/health" && method == Method::GET {
Response::builder()
.status(StatusCode::OK)
.body(full_body("healthy"))
.unwrap()
} else {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(full_body("404 - not found"))
.unwrap()
};
Ok(response)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
loop {
let (stream, _addr) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(io, service_fn(handle_request))
.await
{
eprintln!("connection error: {err}");
}
});
}
}
The routing logic is one long if/else chain. Every new route means another branch. When the number of routes grows beyond a handful, the chain becomes hard to read, hard to test in isolation, and easy to get wrong - for example, you might accidentally match / before /about because of ordering issues.
Now the same three routes in Axum:
// Cargo.toml
// [dependencies]
// axum = "0.8"
// tokio = { version = "1", features = ["full"] }
use axum::{routing::get, Router};
async fn home() -> &'static str {
"Welcome to the home page"
}
async fn about() -> &'static str {
"About this server"
}
async fn health() -> &'static str {
"healthy"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/about", get(about))
.route("/health", get(health));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Each route declares its path, method, and handler in one line. Axum's router matches incoming requests against these declarations and calls the correct handler. If no route matches, Axum returns a 404 response automatically. You do not write any fallback logic.
Manual Routing Mistakes Are Real:
In the Hyper version, the order of the if statements matters. If you check / before /about, a request to / works fine, but if you accidentally reverse the logic or forget a branch, requests silently fall through to the wrong handler or a 404. Axum's router is declarative: you state the routes, and the router handles matching. The opportunity for ordering errors disappears.
Reading a Request Body
Request bodies carry data from the client - form submissions, JSON payloads, uploaded files. In Hyper, reading the body means working with a stream of data frames. Hyper gives you Request<Incoming> where Incoming is a body stream you must consume.
Here is a Hyper server that reads a string body from a POST request:
// Cargo.toml
// [dependencies]
// hyper = { version = "1", features = ["server", "http1"] }
// tokio = { version = "1", features = ["full"] }
// hyper-util = { version = "0.1", features = ["tokio"] }
// http-body-util = "0.1"
use http_body_util::{BodyExt, Full};
use hyper::body::{Bytes, Incoming};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
type BoxBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;
fn full_body(text: String) -> BoxBody {
Full::new(Bytes::from(text))
.map_err(|never| match never {})
.boxed()
}
async fn handle_request(req: Request<Incoming>) -> Result<Response<BoxBody>, hyper::Error> {
if req.method() == Method::POST && req.uri().path() == "/submit" {
// Collect the body into bytes. The body is a stream of data frames.
let body_bytes = req.into_body().collect().await?.to_bytes();
// Convert the bytes to a UTF-8 string.
let body_text = match String::from_utf8(body_bytes.to_vec()) {
Ok(text) => text,
Err(_) => {
return Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(full_body("Invalid UTF-8".to_string()))
.unwrap())
}
};
let response_text = format!("You sent: {}", body_text);
Ok(Response::builder()
.status(StatusCode::OK)
.body(full_body(response_text))
.unwrap())
} else {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(full_body("404 - not found".to_string()))
.unwrap())
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
loop {
let (stream, _addr) = listener.accept().await?;
let io = TokioIo::new(stream);
tokio::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(io, service_fn(handle_request))
.await
{
eprintln!("connection error: {err}");
}
});
}
}
You call req.into_body().collect().await to gather all body frames into one chunk, convert that chunk to bytes, and then decode the bytes as UTF-8. If the body is large, this approach buffers the entire body in memory before you can process it - which is fine for small payloads but potentially problematic for large uploads. Hyper gives you the raw stream and leaves memory management decisions to you.
The Axum equivalent uses an extractor:
// Cargo.toml
// [dependencies]
// axum = "0.8"
// tokio = { version = "1", features = ["full"] }
use axum::{
extract::Json,
routing::{get, post},
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Submission {
name: String,
}
async fn handle_submission(Json(submission): Json<Submission>) -> String {
format!("You sent: {}", submission.name)
}
async fn home() -> &'static str {
"Welcome"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/submit", post(handle_submission));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The Json<Submission> extractor tells Axum: "When this handler is called, parse the request body as JSON, deserialize it into a Submission struct, and hand it to me as submission." Axum reads the body, checks the Content-Type header, parses the JSON, and deserializes it. If the body is malformed JSON, Axum returns a 400 response automatically and does not call your handler.
The type-driven approach is fundamentally different from Hyper's manual approach. In Hyper, you write the steps: read bytes, decode string, parse JSON, handle errors. In Axum, you declare what type you want, and the framework does the steps at runtime while checking type correctness at compile time.
Error Handling Differences
Hyper's error model is explicit but low-level. When something goes wrong - a connection drops, a body read fails, parsing fails - you get an Err value from the function that failed. It is your responsibility to convert that error into a response with the right status code.
In the Hyper body-reading example above, I had to handle the case where the body contained invalid UTF-8. I returned a 400 response manually. I also had to handle the case where the request method or path didn't match, returning a 404 manually. Every error path is hand-written.
Axum has a more systematic model. If an extractor fails (for example, the body is invalid JSON), Axum converts that failure into an error response automatically. The default behavior is a 400 Bad Request for extractor failures (with 415/422 for the JSON cases). A handler that returns an Err is converted through IntoResponse, so you choose the status. One thing Axum does not do by default: a handler that panics does not become a 500 - the panic unwinds the task unless you add tower_http::catch_panic::CatchPanicLayer, which turns panics into 500 responses. You can customize these defaults, but the baseline means many error paths simply do not appear in your code.
Silent Failures Are the Real Danger in Hyper:
When you write a Hyper-only server, the compiler will not tell you if you forgot to handle a specific error case. If your body parsing code has a branch that drops an error value without responding, the request might hang or the connection might close without a response. Axum's error model ensures every error is converted into a response - you get a guarantee that no error is silently swallowed.
When Hyper Directly Makes Sense
Using Hyper without Axum is reasonable in certain situations.
You are building a specialized HTTP tool. If you want a simple proxy that forwards requests, a health-check endpoint for a system service, or a custom protocol that happens to run over HTTP, Hyper gives you exactly what you need without framework overhead.
You need fine-grained control over connection management. Hyper exposes HTTP/1.1 and HTTP/2 connection builders separately. If you need to configure specific HTTP/2 settings or handle connection upgrades in a custom way, you need access to Hyper directly. Axum's higher-level API does not expose every connection-level knob.
You are writing a library, not an application. If your crate needs to speak HTTP but does not want to impose a routing framework on its users, using Hyper keeps the dependency surface minimal. A crate that only needs to send HTTP requests or handle a single incoming connection should not drag in a full routing framework.
When Axum Makes Sense
Axum is the right choice for almost any application where you have multiple endpoints.
REST APIs. A typical JSON API has many routes, method constraints, path parameters, and query strings. Axum's router and extractor system were designed for exactly this shape of application.
Microservices. Each service in a microservices architecture is usually small enough that Axum's overhead is irrelevant, and the ergonomic savings make the code easier to review and maintain.
Backends for SPAs and mobile apps. Any server that needs to expose JSON endpoints to a frontend benefits from Axum's declarative routing and automatic JSON handling.
Real-time backends. Axum integrates with WebSocket and server-sent events through its routing system, which Hyper does not provide out of the box. You can build these on bare Hyper, but you would write significantly more connection-management code.
Most Projects Choose Axum for a Reason:
The Axum crate exists because the patterns it automates - routing, body extraction, error conversion - are needed by nearly every multi-endpoint web service. Choosing Hyper directly means reimplementing those patterns by hand. That is occasionally the right trade-off, but it is a trade-off you should make consciously.
A Practical Decision Framework
When you are starting a new Rust project that needs HTTP, ask yourself these questions in order:
- How many endpoints will this service have? If the answer is zero or one, Hyper alone may be simpler. If the answer is more than one, Axum is almost certainly better.
- Do I need custom connection-level behavior? If you need to tweak HTTP/2 settings, handle unusual upgrades, or manage connections in a way the framework doesn't expose, you may need to use Hyper directly, or at least access Hyper through Axum's lower-level integration points.
- Will other people maintain this code? Axum's declarative routing is easier to read and review than a long
if/elsechain in Hyper. If the codebase will grow, the Axum version will stay manageable longer. - Is this a library or an application? Libraries should prefer Hyper's minimal dependency footprint. Applications should prefer Axum's ergonomics.
These are not hard rules, but they capture the practical reality that Hyper and Axum are not competitors. Hyper is the foundation. Axum is a set of walls and doors built on that foundation. You choose whether to live on the bare foundation or in the completed house.
Common Mistakes Beginners Make
Assuming Hyper has routing. The most frequent error is searching for a hyper::Router type. It does not exist. Hyper parses HTTP messages. Routing is a higher-level concept that Axum provides.
Underestimating the body-handling burden. In Hyper, reading a request body involves working with a stream of data frames. Beginners often try to read the body directly as bytes and discover the type is not Vec<u8> but a stream that must be consumed. Understanding this distinction early saves frustration.
Mixing up the dependency direction. Axum depends on Hyper. Hyper does not depend on Axum. You cannot use Axum without Hyper, because Axum is built on top of it. But you can use Hyper without Axum, because Hyper stands on its own.
Returning the wrong body type from Hyper handlers. The Response type in Hyper is generic over the body type. Beginners often try to return Response<String> and discover that String does not implement the Body trait in the way they expected. The canonical simple body is Full<Bytes> from http_body_util, wrapped in a BoxBody to erase the concrete type.
What Changed Across Versions
Hyper 1.x, released in late 2023 (current: 1.12.0), split the crate into two parts. The core hyper crate contains the HTTP implementation. The hyper-util crate contains I/O adapters, connection utilities, and other supporting code that was previously part of Hyper itself. When you see examples that use hyper_util::rt::TokioIo, that is the bridge between Tokio's async I/O types and Hyper's internal abstractions - and when you see hyper_util::server::conn::auto::Builder, that is the HTTP/1 + HTTP/2 auto-negotiating connection builder described above.
Axum 0.7 and later versions use Hyper 1.x internally. When you add Axum to your project, Hyper comes along as a transitive dependency. This is why the Axum examples in this page do not list Hyper in Cargo.toml directly - it is pulled in automatically.
Version Confusion in Examples:
If you find a Hyper example online that looks completely different from the code on this page, it may be from the Hyper 0.x era. Hyper 0.x had a different API for connection handling and body types. When searching for examples, always check which major version of Hyper the example targets.
Summary
Hyper and Axum are different layers of a Rust web stack. Hyper is the HTTP engine that speaks the wire protocol and manages connections. Axum is a framework that adds routing, type-driven request extraction, and a predictable error model on top. You can build a web server with Hyper alone, and for very small or specialized tools that may be the right choice. For any application with multiple endpoints, Axum gives you a significantly shorter, safer, and more maintainable codebase - not by replacing Hyper, but by organizing the code you would otherwise write by hand.
The relationship to remember is the division of labour: Hyper parses the HTTP message and manages the connection; Axum routes the request to your handler and turns the result into a response. If you need that division spelled out in code, reach for Hyper. If you want the routing and the handler types handled for you, reach for Axum.