routing delete - Handling DELETE Requests in Axum
Learn what the delete function from axum routing does, how to register DELETE request handlers, and how to build delete routes with path parameters and proper status codes.
Imagine you built a small API where users can create notes, read notes, and edit notes. Now a user wants to remove a note they no longer need. HTTP provides a verb for exactly this: DELETE. In Axum, axum::routing::delete is the function that connects a Rust handler to that verb. This page explains what the function does, how to use it, and how to build real delete routes step by step.
What DELETE Means in HTTP
HTTP is the protocol web browsers and clients use to talk to servers. Every HTTP request carries a method - a word that tells the server what kind of action the client wants. GET reads, POST creates, and PUT or PATCH update. DELETE asks the server to remove a resource.
A resource is just a thing the server knows about, like a user, a note, or a product. When a client sends DELETE /notes/42, it is saying "remove note number 42." The server decides what removal actually means: it might delete a database row, mark a record as inactive, or simply forget an entry in memory. The important point is that DELETE signals the intent to remove something.
Axum's routing::delete function exists so you can write a handler that runs only when that exact intent arrives. Without it, your server would have no way to distinguish a DELETE request from a GET request to the same path.
What routing::delete Does
In Axum, you attach handlers to routes using the Router type and its route method. The route method takes a path and a method router - an object that knows which HTTP method it responds to. routing::delete is the function that builds that method router for the DELETE method.
The function signature looks like this (simplified for readability):
pub fn delete<H, T, S>(handler: H) -> MethodRouter<S, Infallible>
You do not need to understand every generic parameter. The important part is: you pass an async function, and you get back a MethodRouter that will only respond to DELETE requests. A MethodRouter is like a route with a built-in filter. It says "I will only run when the HTTP method is DELETE."
Think of delete as a label maker. It takes your handler function and wraps it in a label that says DELETE. Then when you pass that wrapped handler to .route(), Axum knows to only send DELETE requests to it.
Here is the smallest realistic usage:
use axum::{Router, routing::delete};
async fn delete_note() -> &'static str {
"Note deleted"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/notes", delete(delete_note));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
There are two things happening. First, delete_note is an ordinary async function that returns a string. Second, in main, the call delete(delete_note) wraps that function, and .route("/notes", ...) registers it. Now if someone sends DELETE /notes, Axum will call delete_note. If someone sends GET /notes, Axum will not call it - the path matches but the method does not, so Axum returns a 405 Method Not Allowed (with an Allow: DELETE header).
Where the Import Comes From:
The function delete lives inside axum::routing, so you bring it into scope with use axum::routing::delete;. If you forget the import, Rust will tell you that delete is not found. You can also refer to it by its full path: axum::routing::delete(delete_note).
A First Working Delete Route
Let us start with the absolute minimum and run it so you can see the result. Create a new Rust project if you do not have one, add Axum and Tokio to Cargo.toml, and paste the example above into main.rs.
Your Cargo.toml needs these dependencies:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Run the server with cargo run. In a second terminal, send a DELETE request using curl:
curl -X DELETE http://127.0.0.1:3000/notes
The server responds with:
Note deleted
The string the handler returns becomes the response body. The status code is 200 OK by default because returning a string tells Axum "everything went well, here is some text."
Now try a GET request to the same path:
curl http://127.0.0.1:3000/notes
Axum returns a response with status 405 Method Not Allowed. The path exists, but the method router only handles DELETE, and GET is not allowed. This is exactly what the delete function enforces.
Your First Delete Route Works:
If you see Note deleted after the DELETE request and 405 after the GET request, your setup is correct. You have a server that responds only to the DELETE method on the path /notes.
What the Handler Must Look Like
The function you pass to delete - called the handler - must follow certain rules. These rules are the same for all method routers in Axum, but they matter especially here because beginners often get them wrong.
First, the handler must be an async fn. A regular fn will not work. Axum runs handlers inside an async runtime, and the function must be able to await things like database lookups.
Second, the handler must return something that implements the IntoResponse trait. This trait tells Axum how to convert the return value into an HTTP response. Several common types already implement it:
Stringand&'static str- returned as the body with status200 OKStatusCode- just the status code with an empty body(StatusCode, String)- a custom status code plus a bodyResult<T, E>where bothTandEimplementIntoResponse- used for success and error pathsJson<T>fromaxum::Json- serializes a struct into JSON
Here is a handler that returns only a status code:
use axum::http::StatusCode;
async fn delete_note() -> StatusCode {
StatusCode::NO_CONTENT
}
StatusCode::NO_CONTENT is the HTTP code 204, which means "the request succeeded and there is nothing more to say." This is a common choice for DELETE handlers because a deleted resource usually does not need a body in the response.
You can combine a status code with a message:
use axum::http::StatusCode;
async fn delete_note() -> (StatusCode, &'static str) {
(StatusCode::ACCEPTED, "Note deletion accepted")
}
This returns status 202 Accepted with a body of Note deletion accepted. The tuple pattern is useful when you want to communicate more than just "success."
Returning () Is Fine:
A handler that returns () - the unit type - compiles fine: () implements IntoResponse and produces a 200 OK response with an empty body. If you see a trait bound error about IntoResponse, check that your handler returns a type Axum knows how to convert - but () itself is always valid.
Third, handler parameters are extractors. An extractor is anything that implements FromRequestParts or FromRequest. Extractors pull data out of the incoming HTTP request before your handler runs. Path<T> pulls a path parameter out of the URL, and State<T> pulls shared application state out of the router. Extractors that only read parts of the request can appear in any order relative to each other. However, only one extractor can consume the request body (such as Json or String), and it must be the last parameter.
Deleting a Specific Resource with a Path Parameter
A DELETE request almost always targets a specific item. The path /notes is too broad for real APIs. Instead, clients send DELETE /notes/42 to remove note 42. The 42 in the URL is called a path parameter.
In Axum, you declare path parameters inside the route path using curly braces, like /notes/{id}. The handler then extracts the value using the Path extractor:
use axum::{Router, routing::delete, extract::Path, http::StatusCode};
async fn delete_note(Path(id): Path<u64>) -> StatusCode {
println!("Deleting note with id {}", id);
StatusCode::NO_CONTENT
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/notes/{id}", delete(delete_note));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler signature Path(id): Path<u64> tells Axum to take the {id} segment from the URL, try to parse it as a u64, and bind it to the variable id. If someone sends DELETE /notes/42, the handler prints Deleting note with id 42 and returns 204. If someone sends DELETE /notes/not-a-number, Axum cannot parse the segment as a u64, so it returns 400 Bad Request before your handler ever runs.
This parsing behavior is a huge advantage. You never have to manually convert strings to numbers in your delete handler - Axum does it for you and rejects malformed URLs automatically.
Returning Success or Failure Based on What Happened
A real delete handler does not always succeed. The note might not exist. The database might be unavailable. The client needs to know whether deletion actually happened.
The standard pattern is to return a Result where the Ok variant is a success status and the Err variant is a failure status. Both must implement IntoResponse.
use axum::{Router, routing::delete, extract::Path, http::StatusCode};
async fn delete_note(Path(id): Path<u64>) -> Result<StatusCode, StatusCode> {
if id == 1 {
Ok(StatusCode::NO_CONTENT)
} else {
Err(StatusCode::NOT_FOUND)
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/notes/{id}", delete(delete_note));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here the handler only knows about note 1. Sending DELETE /notes/1 returns 204 No Content. Sending DELETE /notes/2 returns 404 Not Found. The Result pattern is the idiomatic way to communicate both outcomes without manually constructing responses.
A beginner mental model that helps: think of your handler as answering a question. "Did you delete the thing?" If yes, return Ok(...). If no, return Err(...). Axum converts both into proper HTTP responses.
A Complete In-Memory Delete Example
So far the handler has not actually stored or removed anything. Let us build a complete example with a shared in-memory data store. The store is a HashMap holding notes by their ID. The delete handler removes an entry from that map.
use axum::{
Router,
routing::delete,
extract::{Path, State},
http::StatusCode,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type SharedStore = Arc<Mutex<HashMap<u64, String>>>;
async fn delete_note(
Path(id): Path<u64>,
State(store): State<SharedStore>,
) -> Result<StatusCode, StatusCode> {
let mut notes = store.lock().unwrap();
match notes.remove(&id) {
Some(_) => Ok(StatusCode::NO_CONTENT),
None => Err(StatusCode::NOT_FOUND),
}
}
#[tokio::main]
async fn main() {
let store: SharedStore = Arc::new(Mutex::new(HashMap::new()));
// Seed the store with two notes so we have something to delete.
store.lock().unwrap().insert(1, "Buy groceries".to_string());
store.lock().unwrap().insert(2, "Read Axum docs".to_string());
let app = Router::new()
.route("/notes/{id}", delete(delete_note))
.with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
There is a lot happening here, so let us go through it piece by piece.
The type alias SharedStore describes an Arc wrapping a Mutex wrapping a HashMap. The Arc lets multiple parts of the program share the same map safely. The Mutex guarantees only one handler can modify the map at a time. Without the mutex, two simultaneous DELETE requests could corrupt the map. Beginners should not worry about the details of Arc and Mutex - just recognize the pattern: shared state in Axum is usually stored behind Arc and Mutex.
The handler takes two extractors: Path(id) and State(store). The State extractor pulls the shared store out of the application state. Then the handler locks the mutex to get exclusive access to the map. The remove method deletes the entry with the given key and returns Some(value) if the entry existed, or None if it did not. That return value drives the response: Some(_) means success, None means the note was not found.
In main, we create the empty store, seed it with two notes, and pass it to .with_state(store). This makes the store available to every handler that uses the State extractor. Without .with_state, the handler would fail to compile because Axum would not know how to provide the SharedStore type.
Test the flow:
curl -X DELETE http://127.0.0.1:3000/notes/1
# 204 No Content (no body)
curl -X DELETE http://127.0.0.1:3000/notes/1
# 404 Not Found (already deleted)
curl -X DELETE http://127.0.0.1:3000/notes/3
# 404 Not Found (never existed)
The first request removes note 1. The second request finds note 1 missing and returns 404. The third request targets a note that never existed.
DELETE Is Idempotent:
The word idempotent means doing the same operation multiple times has the same effect as doing it once. DELETE is idempotent by nature. Deleting note 1 once removes it. Deleting it a second time finds it already gone - which is the same final state. The status codes differ (204 then 404), but the end result for the resource is the same: it is gone. This property matters in distributed systems and retries, but for now, just remember that repeat DELETE requests are safe.
Registering DELETE Alongside Other Methods
A real API has several methods on the same path. You might want GET /notes/1 to read a note and DELETE /notes/1 to delete it. Axum allows this by registering separate routes for the same path with different method routers.
use axum::{
Router,
routing::{delete, get},
extract::{Path, State},
http::StatusCode,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type SharedStore = Arc<Mutex<HashMap<u64, String>>>;
async fn get_note(
Path(id): Path<u64>,
State(store): State<SharedStore>,
) -> Result<String, StatusCode> {
let notes = store.lock().unwrap();
match notes.get(&id) {
Some(note) => Ok(note.clone()),
None => Err(StatusCode::NOT_FOUND),
}
}
async fn delete_note(
Path(id): Path<u64>,
State(store): State<SharedStore>,
) -> Result<StatusCode, StatusCode> {
let mut notes = store.lock().unwrap();
match notes.remove(&id) {
Some(_) => Ok(StatusCode::NO_CONTENT),
None => Err(StatusCode::NOT_FOUND),
}
}
#[tokio::main]
async fn main() {
let store: SharedStore = Arc::new(Mutex::new(HashMap::new()));
store.lock().unwrap().insert(1, "Buy groceries".to_string());
store.lock().unwrap().insert(2, "Read Axum docs".to_string());
let app = Router::new()
.route("/notes/{id}", get(get_note))
.route("/notes/{id}", delete(delete_note))
.with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Both routes share the same path string /notes/{id}. Axum distinguishes them by the HTTP method. When a request arrives, Axum first matches the path, then checks which method router accepts the method. A GET request goes to get_note; a DELETE request goes to delete_note. If neither matches - say a POST request - Axum returns 405 Method Not Allowed.
This separation of concerns is exactly what routing::delete enables. You write one handler for deletion logic and keep it separate from read logic, update logic, and creation logic. Each handler is small and focused on one job.
Returning Different Success Variants
DELETE handlers have flexibility in what they return on success. Some common choices:
StatusCode::NO_CONTENT- the resource is gone, nothing more to say. This is the most common.StatusCode::OKwith a body - sometimes you want to return the deleted item as confirmation.(StatusCode, String)- a status plus a human-readable message.Json<T>- a JSON representation of the result.
Here is an example that returns the deleted value:
use axum::{
Router,
routing::delete,
extract::{Path, State},
http::StatusCode,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
type SharedStore = Arc<Mutex<HashMap<u64, String>>>;
async fn delete_note(
Path(id): Path<u64>,
State(store): State<SharedStore>,
) -> Result<(StatusCode, String), StatusCode> {
let mut notes = store.lock().unwrap();
match notes.remove(&id) {
Some(deleted) => Ok((StatusCode::OK, format!("Deleted: {}", deleted))),
None => Err(StatusCode::NOT_FOUND),
}
}
#[tokio::main]
async fn main() {
let store: SharedStore = Arc::new(Mutex::new(HashMap::new()));
store.lock().unwrap().insert(1, "Buy groceries".to_string());
let app = Router::new()
.route("/notes/{id}", delete(delete_note))
.with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
When you delete note 1, the response is 200 OK with body Deleted: Buy groceries. Returning the deleted value is useful for clients that want to confirm what was removed, or for audit logging on the client side.
The choice between 204 and 200 is purely a design decision. 204 is cleaner when there is no need for a body. 200 with a body is better when the client benefits from knowing what was deleted.
What Beginners Usually Get Wrong
Several mistakes show up repeatedly when people first use routing::delete. Knowing them ahead of time will save you debugging.
Forgetting to Import delete:
If your code does not compile and the error says something like cannot find function delete, check your imports. The function comes from axum::routing, not from the axum crate root. Add use axum::routing::delete; or refer to it as axum::routing::delete(handler).
Another common error is writing a handler that is not async:
// This will NOT work
fn delete_note() -> &'static str {
"Deleted"
}
Axum requires handlers to be async functions. Adding the async keyword fixes it:
// This works
async fn delete_note() -> &'static str {
"Deleted"
}
A third mistake is mismatching the path parameter type. If your route says /notes/{id} but your handler extracts Path(id): Path<u32> and the URL contains a number larger than u32 can hold, Axum returns 400 Bad Request. The parse fails before your handler runs. Choose a type wide enough for your IDs - u64 is a safe default for most cases.
A fourth issue is forgetting .with_state(). If your handler uses State<SharedStore> but you never call .with_state(store), Rust will give you a confusing error about a missing state type. Always check that every State<T> extractor has a matching .with_state call on the router.
A fifth trap is expecting a handler that returns () to send a 204 No Content response. It does not: () compiles fine and sends 200 OK with an empty body. If you want 204, return StatusCode::NO_CONTENT explicitly instead of ().
Locking the Mutex:
Using store.lock().unwrap() works for learning, but in a production system the mutex could become poisoned if a previous handler panicked while holding the lock. The unwrap would then panic too. For production code, handle the error by mapping it to a 500 Internal Server Error. For this tutorial, unwrap keeps the example readable.
How to Think About routing::delete
When you are building an Axum API and you need to support deletion, follow this sequence in your head:
- Identify the resource that can be deleted.
- Write an async handler that removes the resource and returns a meaningful status.
- Wrap the handler with
delete(...). - Register it with
.route("/path", delete(handler)). - If the handler needs shared data, add
Stateand.with_state.
The delete function itself is small - it just stamps a handler with the DELETE method. All the interesting work lives in your handler. Focus your attention on what "remove this resource" means in your application, and let routing::delete handle the HTTP method filtering.
Summary
The routing::delete function is a method router constructor: it takes an async handler and returns a MethodRouter configured to respond only to HTTP DELETE requests. You pair it with Router::route to register paths like /notes/{id} for deletion. Handlers can use Path to read the target ID, State to access shared data, and return Result<StatusCode, StatusCode> to signal success or failure cleanly.
The single most important insight is that routing::delete separates which method a route responds to from what the handler does. Once you understand that separation, the rest is ordinary Rust: parse the ID, remove the resource, decide what to return.
What this unlocks is the ability to build a complete REST API where every HTTP method on a path does a different job. You can now register GET, POST, PUT, PATCH, and DELETE side by side, each with a dedicated handler. The next natural step is combining multiple method routers on the same path using chaining, which lets you attach several methods in a single expression instead of repeating .route() for each one.