CRUD UPDATE PUT

Learn how a PUT handler replaces a whole user row in Postgres with sqlx and returns 404 when the id does not exist

A PUT handler that updates a user takes an id from the URL and a complete user in the JSON body, replaces every field of that row in the users table, and sends the updated row back with status 200. When no row has that id, the handler answers 404. PUT means "replace the whole thing", so the body must carry every field, and any field left out is an error before the handler runs.

Where This Fits

The create handler writes new rows and the read handlers fetch them back. This page adds the first handler that changes a row that already exists. It takes the id from the path, like the single-row read, and a full JSON body, like the create handler, and it runs an UPDATE that writes every column at once. The partial update handler shares the same route and the same id, and it differs in exactly one way: it accepts a body with only the fields that change.

Think of a form that reprints a whole record. A clerk pulls the file for a patient, throws the old form away, and files a fresh form with every field filled in again. The clerk does not patch one line on the old form. The new form must be complete, because the old one is gone. PUT works the same way. The body is the fresh form, and the database replaces the row with it.

The Smallest Working Version

Create a project with these files. It has one route, PUT /users/{id}, and nothing else.

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

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }

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

The sqlx line needs four features. runtime-tokio runs sqlx on the Tokio runtime, postgres adds the Postgres driver, macros turns on the query_as! macro used below, and derive turns on the FromRow derive used on the User struct. The tower dev-dependency is only for the test near the end of this page.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/handlers.rs
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};

use crate::errors::AppError;

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct ReplaceUser {
    pub name: String,
    pub email: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_user_input(name: &str, email: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    Ok(())
}

pub async fn replace_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(input): Json<ReplaceUser>,
) -> Result<Json<User>, AppError> {
    check_user_input(&input.name, &input.email)?;
    let user = sqlx::query_as!(
        User,
        "UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING id, name, email",
        input.name,
        input.email,
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(user))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::put};
use handlers::replace_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", put(replace_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Create the table and one row before running the server:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW());"
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "TRUNCATE users RESTART IDENTITY;"
psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com');"

The TRUNCATE line empties the table and resets the id sequence to 1, so the row inserted afterwards gets id 1 and the outputs below match. Run it whenever an earlier page already left rows in the table.

Start the server with the connection string in the environment:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo run

The terminal prints Server running at http://127.0.0.1:3000 and waits. In a second terminal, replace the user with id 1:

curl -X PUT http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Rao", "email": "asha.rao@example.com"}'

The server answers with status 200 and the updated row:

{"id":1,"name":"Asha Rao","email":"asha.rao@example.com"}

The id stays 1, because the UPDATE changes the name and email, not the id. The created_at column keeps its original value too, because the UPDATE does not mention it. Replace a missing id, and the answer is a 404:

curl -i -X PUT http://127.0.0.1:3000/users/99 \
  -H "Content-Type: application/json" \
  -d '{"name": "Nobody", "email": "nobody@example.com"}'
HTTP/1.1 404 Not Found
content-type: application/json
content-length: 30

{"error":"resource not found"}

Working Setup:

If the first curl prints the updated user with the new name and email and the same id, and the second prints a 404, the handler works end to end. The row was replaced, the id survived, and the missing row was answered instead of creating a new one.

Understanding the Handler Line by Line

The handler has three extractors and one query, and each piece carries over from the handlers before it. The new piece is the UPDATE statement, and the rest is the same shape with a different job.

The three extractors

pub async fn replace_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(input): Json<ReplaceUser>,
) -> Result<Json<User>, AppError> {

State(pool) pulls the connection pool from router state. Path(id) parses the {id} part of the URL into an i32. Json(input) parses the request body into a ReplaceUser value. The ReplaceUser struct has both fields as plain String values, not Option, so a body missing either field is rejected before the handler runs. That is the whole difference between a full replacement and a partial one, and it lives in this struct: required fields mean the body must be complete.

The return type is Result<Json<User>, AppError>. A successful replacement answers 200 with the updated user, and Axum supplies the 200 because a plain Json return means success with the default status.

The validation check

    check_user_input(&input.name, &input.email)?;

The same validation helper the create handler uses runs here, before any database call. A PUT body with an empty name or a malformed email is refused with a 422, and the row is left untouched. Validation on update matters as much as on create, because a bad value written over a good row destroys data that was correct. The check runs first so a failed request changes nothing.

The UPDATE with RETURNING

    let user = sqlx::query_as!(
        User,
        "UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING id, name, email",
        input.name,
        input.email,
        id
    )
    .fetch_one(&pool)
    .await?;

The SQL sets both columns at once. SET name = $1, email = $2 assigns the new name and the new email, and WHERE id = $3 limits the change to the one row with the given id. The placeholder numbers follow the value list: $1 is input.name, $2 is input.email, and $3 is id. The order of the values is the order of the placeholders, and the id comes last because it appears last in the SQL.

RETURNING id, name, email makes the UPDATE send the changed row back, the same way it does for an INSERT. Without it, the handler would know only how many rows changed, and it would need a second SELECT to show the client the new values. fetch_one expects exactly one row back. When the id matches a row, Postgres updates it and returns it. When the id matches nothing, the UPDATE changes zero rows, RETURNING returns nothing, and fetch_one fails with RowNotFound, which the shared mapping turns into a 404. The missing-row answer comes free from the same chain that answers the single-row read, and the handler never checks the row count itself.

Bind Order Is Placeholder Order:

The values fill $1, $2, and $3 strictly in order. Putting id first in the value list would bind the id into the name column, and the code would still compile, because the name column accepts integers as text only if Postgres can cast them, and an i32 bound to a text placeholder fails at runtime instead. Read the placeholder numbers against the value list before running the server.

The Concept Behind Full Replacement

PUT and PATCH are two verbs with different promises. PUT promises that the body is the whole new state of the resource. The server takes the body, writes every field from it, and the row afterwards holds exactly what the body said, no more and no less. PATCH promises that the body holds only the changes. The server takes the body, writes the fields it names, and leaves the rest alone. The two verbs share a route and an id, and they differ in what the body means.

The difference lives in the input struct. ReplaceUser has name: String and email: String, both required, so the client must send both. A body with only a name is rejected by the Json extractor, because email is missing, and the handler never runs. That rejection is the contract working as designed: a client that meant to change only the name used the wrong verb, and the server refuses the request instead of guessing what the email should become.

A beginner can think of PUT as repainting a whole room and PATCH as touching up one wall. Repainting needs the colour for every wall, because every wall gets painted. Touching up needs only the colour of the one wall that changes. Sending half a repaint is not a touch-up, and the server should not treat it as one.

Why UPDATE with RETURNING Beats UPDATE Then SELECT

The handler could run the UPDATE with execute, check how many rows changed, and then run a SELECT to fetch the new values. That version works, and it costs a second round trip, plus a decision about what to do when the row count is zero. The RETURNING version does the same work in one statement. Postgres updates the row and hands back the new values in the same step, so there is no gap where another request could change the row between the UPDATE and the SELECT, and the handler code has no row-count check to write.

The row-count version also has a subtle failure. Between the UPDATE and the SELECT, a delete could remove the row, and the SELECT would then find nothing, turning a successful update into a confusing 404. The RETURNING version cannot hit that gap, because the values come from the row at the moment it was updated. One statement, one round trip, one answer.

PUT Does Not Create a Missing Row

Some APIs treat a PUT to a missing id as a create, writing a new row with that id. This handler does not. A PUT to id 99 answers 404, and no row appears. The reason is the id. The id is assigned by the database sequence, and the client cannot pick it. Creating a row with a client-chosen id would fight the sequence, and the next row the database creates on its own could collide with it. The create endpoint owns id assignment, and the update endpoint only changes rows the database already created.

There is a SQL feature, sometimes called upsert, that inserts a row when the key is missing and updates it when the key exists. It has its own uses, and it is not what this handler does. This handler is a pure replacement: the row must exist first, and the 404 says so when it does not.

A Richer Complete Example

The smallest version replaces one user. A realistic session replaces a user, sends a bad body, and sends an incomplete body, and each failure leaves the row unchanged. Start with the row from the smallest example, then send a body with an empty name:

curl -i -X PUT http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "", "email": "asha.rao@example.com"}'
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 34

{"error":"name must not be empty"}

Read the row back, and it still holds the values from the successful PUT, because the 422 stopped the request before the UPDATE ran:

curl http://127.0.0.1:3000/users/1
{"id":1,"name":"Asha Rao","email":"asha.rao@example.com"}

Send a body missing the email, and Axum rejects it before the handler runs, because ReplaceUser.email is a required String:

curl -i -X PUT http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha"}'
HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
content-length: 99

Failed to deserialize the JSON body into the target type: missing field `email` at line 1 column 16

That 422 comes from the Json extractor, not from the app, and its body is plain text, not the shared JSON shape. The extractor failed to turn the body into a ReplaceUser before the handler ran, so the shared error type never got a chance to answer. The message names the missing field and the position in the body where the parse stopped, which is enough to see the mistake. The row is untouched, because the handler never ran.

Send a duplicate email, an email another user already holds, and the unique constraint refuses the UPDATE. The failure becomes a 500 through the shared mapping, and the row keeps its old email:

psql "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" -c "INSERT INTO users (name, email) VALUES ('Ravi', 'ravi@example.com');"
curl -i -X PUT http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Rao", "email": "ravi@example.com"}'
HTTP/1.1 500 Internal Server Error
content-type: application/json
content-length: 32

{"error":"something went wrong"}

Repeating a PUT Is Safe

Sending the same PUT twice leaves the row in the same state as sending it once. The second request sets the name and email to the values they already hold, and the response is the same row. That property has a name, idempotence, which means repeating an operation has the same effect as doing it once. PUT is idempotent by design, because the body states the whole new state, and writing the same state twice changes nothing the second time.

Idempotence matters when a client retries a request. A network can drop a response after the server already applied the update, and the client, unsure whether the request landed, sends it again. With PUT, the retry is harmless. The row ends up exactly as the client wanted, whether the request ran once or twice. A create request does not share this property, because sending it twice creates two rows, which is why clients retry PUT freely and retry POST with care.

Same Body Twice, Same Row:

Idempotence is a promise about the outcome, not about the work. The second PUT still runs an UPDATE, and Postgres still writes the row. The promise is that the row after the second PUT holds the same values as after the first, so the client cannot tell how many times the request ran by looking at the data.

What Happens Without the WHERE Clause

An UPDATE without a WHERE clause changes every row in the table. The SQL below would set every user's name and email to the same values, and fetch_one would then fail, because the UPDATE would return many rows. The failure would be a 500, and the damage would already be done, because the UPDATE runs before the error surfaces.

// Wrong - every row in the table gets the same name and email
let user = sqlx::query_as!(
    User,
    "UPDATE users SET name = $1, email = $2 RETURNING id, name, email",
    input.name,
    input.email
)
.fetch_one(&pool)
.await?;

The WHERE id = $3 clause is the only thing standing between a single-row update and a whole-table rewrite. Read it before running any UPDATE, and never write an UPDATE in a handler without one. The compile-time check cannot catch a missing WHERE, because the SQL is valid without it. Only the reader can.

The Request Flow

The path of a PUT request through the app looks like this:

Client sends PUT /users/1 with a full JSON body
        |
        v
Axum parses the body into ReplaceUser
        |
        v
Handler checks the name and email
        |
        +-- bad input --> 422 with {"error": message}
        |
        v
query_as! runs UPDATE ... RETURNING
        |
        +-- no row matched --> RowNotFound --> 404 with {"error": "resource not found"}
        |
        +-- database failure --> 500 with {"error": "something went wrong"}
        |
        v
Postgres updates the row and returns it
        |
        v
Handler returns 200 with the updated user as JSON

Validation runs before the database, and the missing-row check happens inside the query itself, through fetch_one. The handler body holds no branching for the 404, because the query result carries it.

Testing the PUT Handler

The test below inserts a row, replaces it through the router, and checks that the response holds the new values and the same id. A second test replaces a missing id and checks the 404.

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

async fn pool() -> sqlx::PgPool {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    create_pool(&database_url).await.unwrap()
}

#[tokio::test]
async fn put_user_replaces_the_row() {
    let pool = pool().await;
    sqlx::query!("DELETE FROM users").execute(&pool).await.unwrap();
    sqlx::query!("INSERT INTO users (name, email) VALUES ('Asha', 'asha@example.com')")
        .execute(&pool)
        .await
        .unwrap();
    let row = sqlx::query!("SELECT id FROM users WHERE email = 'asha@example.com'")
        .fetch_one(&pool)
        .await
        .unwrap();
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("PUT")
                .uri(format!("/users/{}", row.id))
                .header("Content-Type", "application/json")
                .body(Body::from(
                    r#"{"name": "Asha Rao", "email": "asha.rao@example.com"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let text = String::from_utf8(body.to_vec()).unwrap();
    assert!(text.contains("\"name\":\"Asha Rao\""));
    assert!(text.contains("\"email\":\"asha.rao@example.com\""));
    assert!(text.contains(&format!("\"id\":{}", row.id)));
}

#[tokio::test]
async fn put_missing_user_returns_404() {
    let pool = pool().await;
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("PUT")
                .uri("/users/999999")
                .header("Content-Type", "application/json")
                .body(Body::from(
                    r#"{"name": "Nobody", "email": "nobody@example.com"}"#,
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

The first test reads the id back from the database after inserting, instead of assuming it is 1, because the sequence keeps counting across runs. It checks the id in the response, because a PUT must keep the id unchanged. Run them with the database URL set:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo test -- --test-threads=1
test put_user_replaces_the_row ... ok
test put_missing_user_returns_404 ... ok

The --test-threads=1 flag runs the tests one at a time. The tests share one table, and running them at the same time could make one test delete rows another test is reading.

Common Beginner Mistakes

Swapping the bind order

// Wrong - the id lands in the name column and the name lands in the id filter
let user = sqlx::query_as!(
    User,
    "UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING id, name, email",
    id,
    input.name,
    input.email
)
.fetch_one(&pool)
.await?;

The value list must follow the placeholder numbers, not the order the handler received the values. Here $1 gets the id, $2 gets the name, and $3 gets the email, so the UPDATE writes the id into the name column and compares the email string against the id column. The compile-time check may catch the type mismatch, because an i32 does not decode as text, but it cannot catch every swap, especially between two text values. Read the list against the SQL every time.

Forgetting RETURNING and selecting afterwards

// Wrong - two round trips and a gap where the row can change
sqlx::query!(
    "UPDATE users SET name = $1, email = $2 WHERE id = $3",
    input.name,
    input.email,
    id
)
.execute(&pool)
.await?;
let user = sqlx::query_as!(User, "SELECT id, name, email FROM users WHERE id = $1", id)
    .fetch_one(&pool)
    .await?;

This version works when nothing else touches the row, and it fails quietly when something does. The SELECT can return values written by a concurrent request, or nothing at all if the row was deleted in between. RETURNING gives the values from the row at the moment it was updated, in the same statement. Use it.

Treating a missing body field as empty

// Wrong - a missing field becomes an empty string and wipes the stored value
#[derive(Debug, Deserialize)]
pub struct ReplaceUser {
    pub name: String,
    #[serde(default)]
    pub email: String,
}

The #[serde(default)] attribute tells serde to use an empty string when the field is missing, so a body with only a name passes validation of the struct shape and then fails the handler check with a 422, or worse, writes an empty email if the check is skipped. A full replacement must require every field, and the rejection of an incomplete body is the contract, not a bug. Leave default off the fields of a PUT body, and let the extractor reject what is incomplete.

An UPDATE Without WHERE Rewrites the Table:

The most dangerous line on this page is an UPDATE with no WHERE clause. It compiles, it runs, and it changes every row. The WHERE id = $3 clause is the only guard, and the compiler cannot check for it. Before running any UPDATE, read the statement and confirm the WHERE names the id from the path.

Checking That Everything Compiles

Before running cargo run, run cargo check. The query_as! macro needs the database at compile time, so DATABASE_URL must be set for the check as well as for the run:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo check

If the output ends with a Finished line and no errors, there are no type errors, and the SQL passed the compile-time check against the real table. Then run cargo run to start the server.

Final Complete Example

Here is everything from this page put together. The project has one route, one handler, and the shared error and pool files.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}

impl From<sqlx::Error> for AppError {
    fn from(error: sqlx::Error) -> Self {
        match error {
            sqlx::Error::RowNotFound => AppError::NotFound,
            other => {
                eprintln!("database error: {other}");
                AppError::InternalError
            }
        }
    }
}
src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions};

pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)
        .connect(database_url)
        .await
}
src/handlers.rs
use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};

use crate::errors::AppError;

#[derive(Debug, Serialize, FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
}

#[derive(Debug, Deserialize)]
pub struct ReplaceUser {
    pub name: String,
    pub email: String,
}

fn valid_email(email: &str) -> bool {
    let Some((local, domain)) = email.split_once('@') else {
        return false;
    };
    !local.is_empty() && domain.contains('.')
}

fn check_user_input(name: &str, email: &str) -> Result<(), AppError> {
    if name.trim().is_empty() {
        return Err(AppError::ValidationError(
            "name must not be empty".to_string(),
        ));
    }
    if !valid_email(email) {
        return Err(AppError::ValidationError(
            "email must look like name@example.com".to_string(),
        ));
    }
    Ok(())
}

pub async fn replace_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(input): Json<ReplaceUser>,
) -> Result<Json<User>, AppError> {
    check_user_input(&input.name, &input.email)?;
    let user = sqlx::query_as!(
        User,
        "UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING id, name, email",
        input.name,
        input.email,
        id
    )
    .fetch_one(&pool)
    .await?;
    Ok(Json(user))
}
src/lib.rs
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::put};
use handlers::replace_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", put(replace_user))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Run it with:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch12_crud" cargo run

Then replace a user with:

curl -X PUT http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Rao", "email": "asha.rao@example.com"}'

Summary

A PUT handler is a full replacement with a strict contract: the body carries every field, the id comes from the path and never changes, and the row must already exist. The SQL writes both columns in one statement, RETURNING hands the updated row back without a second query, and fetch_one turns a missing row into a 404 without a row-count check in the handler. Validation runs first, so a failed request changes nothing, and the request is idempotent, so a client can safely send it twice.

The decision to carry forward is the choice between the two update verbs. When the client holds the whole new state, PUT is the verb, and the required fields in the input struct enforce the contract. When the client holds only the changes, the partial update is the verb, and its input struct says so with optional fields. The SQL differs by one idea, whether a column keeps its old value when the body is silent, and that one idea is the whole difference between the two handlers.