CRUD UPDATE PATCH

Learn how a PATCH handler changes only the fields a client sends with sqlx COALESCE and leaves the rest of the user row untouched

A PATCH handler that updates a user takes an id from the URL and a JSON body with only the fields that change, writes those fields into the users table, leaves every other field alone, and sends the updated row back with status 200. When no row has that id, the handler answers 404. PATCH means "change what I name", so the body may hold one field, both fields, or neither, and the row keeps whatever the body does not mention.

Where This Fits

The PUT handler replaces the whole row, and it refuses a body that leaves a field out. This page adds the handler for the other half of that job: changing one field while the rest of the row stays as it is. It shares the same route and the same id, and it differs in exactly two places: the input struct holds optional fields, and the SQL uses COALESCE to keep a column when the body is silent about it.

Think of a form with two lines, name and email, where the client crosses out the lines it does not want to change. The clerk rewrites only the lines left visible and copies the rest from the old form. The crossed-out lines are the missing fields, and the clerk does not erase them. PATCH works the same way. The body names the changes, and the database keeps the rest.

The Smallest Working Version

Create a project with these files. It has one route, PATCH /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 PatchUser {
    pub name: Option<String>,
    pub email: Option<String>,
}

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

pub async fn patch_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(input): Json<PatchUser>,
) -> Result<Json<User>, AppError> {
    if let Some(name) = &input.name {
        if name.trim().is_empty() {
            return Err(AppError::ValidationError(
                "name must not be empty".to_string(),
            ));
        }
    }
    if let Some(email) = &input.email {
        if !valid_email(email) {
            return Err(AppError::ValidationError(
                "email must look like name@example.com".to_string(),
            ));
        }
    }
    let user = sqlx::query_as!(
        User,
        "UPDATE users SET name = COALESCE($1, name), email = COALESCE($2, email) 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::patch};
use handlers::patch_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", patch(patch_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, change only the name of the user with id 1:

curl -X PATCH http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Rao"}'

The server answers with status 200 and the updated row. The name changed, and the email stayed exactly as it was:

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

Patch a missing id, and the answer is a 404:

curl -i -X PATCH http://127.0.0.1:3000/users/99 \
  -H "Content-Type: application/json" \
  -d '{"name": "Nobody"}'
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 user with the new name and the old email, and the second prints a 404, the handler works end to end. The named field changed, the unnamed field 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, like the PUT handler, and the differences are small but load-bearing. The input struct, the validation, and the SQL each carry one half of the partial-update idea.

The optional fields

#[derive(Debug, Deserialize)]
pub struct PatchUser {
    pub name: Option<String>,
    pub email: Option<String>,
}

Option<String> is a Rust type that is either Some with a string inside, or None with nothing inside. A JSON body that includes "name" gives Some with that name, and a body that leaves "name" out gives None. The Json extractor fills in None for a missing field automatically, because Option fields are optional by default in serde, the serialization library behind Json. That is the whole contract of the input struct: the client may send either field, both fields, or neither, and the handler receives exactly what the client sent, with None marking what it did not.

The per-field validation

    if let Some(name) = &input.name {
        if name.trim().is_empty() {
            return Err(AppError::ValidationError(
                "name must not be empty".to_string(),
            ));
        }
    }
    if let Some(email) = &input.email {
        if !valid_email(email) {
            return Err(AppError::ValidationError(
                "email must look like name@example.com".to_string(),
            ));
        }
    }

The handler checks only the fields the client sent. if let Some(name) = &input.name runs the block when the name is present and skips it when the name is None. A missing name is not an error here, because the client is allowed to leave it out. A present name that is empty after trimming is an error, because an empty name is never a valid value, whether it arrives in a full replacement or a partial one. The same logic applies to the email. The validation helper from the create handler cannot be reused as it stands, because it takes two plain strings and this handler has two options, so the checks are written inline, one if let per field.

A subtle point is the & in &input.name. The check borrows the name, because the value is moved into the query later, and a move after a borrow would fail to compile. Borrowing for the check and moving for the query keeps both uses legal, and the borrow ends before the move happens.

The UPDATE with COALESCE

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

COALESCE is a SQL function that returns its first argument when that argument is not null, and its second argument when the first one is null. COALESCE($1, name) means "use the new name when the client sent one, and keep the stored name when it did not". The trick works because an Option<String> bound into a placeholder becomes SQL NULL when it is None, and the value itself when it is Some. The database sees NULL for a missing field, COALESCE falls through to the column, and the column keeps its old value.

The placeholder numbers follow the value list, as always: $1 is input.name, $2 is input.email, and $3 is id. RETURNING id, name, email sends the changed row back, and fetch_one turns a missing row into RowNotFound, which the shared mapping turns into a 404. The handler returns the updated row as JSON with status 200.

A Null in the Body Is Not a Missing Field:

A JSON body of {"name": null} is not the same as a body with no name field. Serde parses an explicit null into None, so this handler treats it like a missing field and keeps the old name. That is convenient, but it also means a client cannot use PATCH to set a field back to empty, because there is no empty value for a NOT NULL column to hold. A body that names a field with null is a request to leave it alone, not a request to clear it.

The Concept Behind COALESCE

COALESCE takes any number of arguments and returns the first one that is not null. With two arguments, it is a choice between a new value and the old one. The pattern SET column = COALESCE($1, column) reads as "set the column to the new value if one was given, otherwise set it to itself", and setting a column to itself is a change that changes nothing. The row is rewritten with the same value in that column, and Postgres treats it as an update of the row either way, refreshing the stored values for the columns that did change.

The pattern only works because the input uses Option. A plain String can never be null, so there would be no way to tell "the client sent nothing" from "the client sent a value". The Option carries the absence through the handler and into the placeholder, and the placeholder carries it into the SQL as NULL, where COALESCE reads it. Three layers, one idea: absence means keep.

A beginner can think of COALESCE as a fallback chain. The first choice is the new value. If there is no new value, the second choice is the old value. The chain always lands on something, so the column always ends up with a defined value, never a null.

Why PATCH Validates Only What Arrives

The PUT handler validates both fields, because both fields are required and both are about to be written. The PATCH handler validates only the fields present in the body, because only those fields are about to be written. Validating a missing field would be nonsense: there is no value to check, and the row already holds a value that passed validation when it was written. The rule is simple to state and easy to get wrong. Validate what the request is about to change, and nothing else.

The same rule explains why the two if let blocks check different things. The name check looks for emptiness, because a name must not be empty. The email check looks for shape, because an email must look like an email. Each check guards the value it names, and neither check runs for a field the client left out.

PATCH Is Not Idempotent in the Same Way PUT Is

Sending the same PUT twice leaves the row in the same state, because the body states the whole new state. Sending the same PATCH twice also leaves the row in the same state, because the second PATCH writes the same values the first one wrote. In that narrow sense, PATCH is idempotent too. The difference shows up when the body is empty or when two different PATCH requests overlap. An empty PATCH body, {}, changes nothing and returns the row as it is, which is harmless but useless. Two PATCH requests that change different fields can interleave, and the final row holds both changes, because each one kept the fields it did not name. Two PUT requests that interleave can overwrite each other, because each one writes every field, and the last writer wins on all of them.

That is why clients use PATCH for small edits from a form, where one field changes at a time, and PUT for whole-record saves, where the client holds the complete new state. The verb should match what the client knows. A client that knows only the new name should send a PATCH, and a client that knows the whole record should send a PUT.

A Richer Complete Example

The smallest version changes one field. A realistic session changes each field on its own, sends an empty body, and sends a bad value, and each request shows which fields moved and which stayed. Start with the row from the smallest example, which now holds name "Asha Rao" and email "asha@example.com", and change only the email:

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

The name survived from the earlier PATCH, and the email changed. Change both fields at once, and both move:

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

Send an empty body, and the row comes back unchanged. The UPDATE still runs, COALESCE keeps both columns, and RETURNING sends the row back as it is:

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

Send a bad email, and the 422 stops the request before the UPDATE runs, so the row keeps its old values:

curl -i -X PATCH http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"email": "not-an-email"}'
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 49

{"error":"email must look like name@example.com"}

An Empty PATCH Is Valid but Pointless:

A PATCH with an empty body is not an error. The handler runs the UPDATE, both columns keep their values, and the row comes back unchanged. Some APIs reject an empty PATCH with a 422, on the grounds that a request that changes nothing is probably a client bug. This handler accepts it, because the contract is about which fields change, and "none of them" is a valid answer to that question.

The Wrong Way to Write a Partial Update

A beginner sometimes writes a partial update by reading the row first, filling in the missing fields in Rust, and then running a full UPDATE with the merged values. That version works, and it has two problems the COALESCE version does not. It costs an extra SELECT, and between the SELECT and the UPDATE another request can change the row, so the merged values can overwrite a change the handler never saw. The COALESCE version does the merge inside the database, in one statement, with no gap for another request to slip into.

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

unwrap_or is a method on Option that returns the value inside when it is Some, and the fallback value when it is None. The code reads fine, and the race is real: the row fetched in the first query can change before the second query runs, and the UPDATE then writes the stale values back over the newer ones. The COALESCE version never reads the row in Rust at all, so there is nothing stale to write back. Let the database do the merge.

What Happens When the Body Names an Unknown Field

Serde ignores JSON keys the struct does not have, so a PATCH body with an extra "age" key runs the same as a body without it. The extra key is dropped during parsing, and the handler never sees it. That is the same behaviour as the create handler, and it is worth knowing because a client that misspells "name" as "nane" gets a surprising result: the misspelled key is ignored, the name stays None, and the PATCH changes nothing, returning the row unchanged with a 200. The request looks successful, and nothing happened. A client debugging that response should check the spelling of its field names first.

The Request Flow

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

Client sends PATCH /users/1 with a partial JSON body
        |
        v
Axum parses the body into PatchUser, missing fields become None
        |
        v
Handler checks only the fields that are present
        |
        +-- bad value --> 422 with {"error": message}
        |
        v
query_as! runs UPDATE ... COALESCE ... RETURNING
        |
        +-- no row matched --> RowNotFound --> 404 with {"error": "resource not found"}
        |
        +-- database failure --> 500 with {"error": "something went wrong"}
        |
        v
Postgres keeps unnamed columns and returns the row
        |
        v
Handler returns 200 with the updated user as JSON

The COALESCE step is the only part of the flow the PUT handler does not have. Everything else, the parsing, the validation, the missing-row chain, and the response, is the same shape.

Testing the PATCH Handler

The test below inserts a row, patches only its name, and checks that the email survived. A second test patches a missing id and checks the 404, and a third test sends a bad email and checks the 422.

tests/patch_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()
}

async fn seed(pool: &sqlx::PgPool) -> i32 {
    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();
    sqlx::query!("SELECT id FROM users WHERE email = 'asha@example.com'")
        .fetch_one(pool)
        .await
        .unwrap()
        .id
}

#[tokio::test]
async fn patch_user_changes_only_the_named_field() {
    let pool = pool().await;
    let id = seed(&pool).await;
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("PATCH")
                .uri(format!("/users/{id}"))
                .header("Content-Type", "application/json")
                .body(Body::from(r#"{"name": "Asha Rao"}"#))
                .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@example.com\""));
}

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

#[tokio::test]
async fn patch_bad_email_returns_422() {
    let pool = pool().await;
    let id = seed(&pool).await;
    let router = app(pool);
    let response = router
        .oneshot(
            Request::builder()
                .method("PATCH")
                .uri(format!("/users/{id}"))
                .header("Content-Type", "application/json")
                .body(Body::from(r#"{"email": "not-an-email"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

The first test checks both the changed field and the unchanged field, because a PATCH test that only checks the changed field would pass even if the handler wiped the email. The seed helper inserts a fresh row and returns its id, so the tests never assume an id value. 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 patch_user_changes_only_the_named_field ... ok
test patch_missing_user_returns_404 ... ok
test patch_bad_email_returns_422 ... 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

Using plain String fields in the patch struct

// Wrong - a missing field is rejected instead of left alone
#[derive(Debug, Deserialize)]
pub struct PatchUser {
    pub name: String,
    pub email: String,
}

With plain String fields, a body that names only the name is rejected before the handler runs, because the email is missing, and the handler behaves exactly like PUT. The Option is what makes the fields optional, and without it there is no partial update at all. The struct is the contract, and the contract must say which fields may be absent.

Writing None into the column

// Wrong - a missing name becomes NULL, which the NOT NULL column refuses
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?;

Without COALESCE, a None name binds as SQL NULL, and the UPDATE tries to write NULL into a NOT NULL column. Postgres refuses, the failure becomes a 500, and the client gets a server error for a request that should have succeeded. COALESCE is the piece that turns "no value given" into "keep the old value". Never bind an Option straight into a NOT NULL column.

Forgetting to validate the fields that are present

// Wrong - a present but empty name sails through to the database
let user = sqlx::query_as!(
    User,
    "UPDATE users SET name = COALESCE($1, name), email = COALESCE($2, email) WHERE id = $3 RETURNING id, name, email",
    input.name,
    input.email,
    id
)
.fetch_one(&pool)
.await?;

Skipping validation because the fields are optional is a common slip. Optional means the client may leave the field out, not that any value it sends is fine. An empty name in a PATCH is just as invalid as an empty name in a PUT, and it must be refused with a 422 before the UPDATE runs. Validate what arrives, and skip what does not.

COALESCE Cannot Tell Absent From Null:

The COALESCE pattern treats a missing field and an explicit JSON null the same way, because both become None in Rust and NULL in SQL. A client that wants to clear a field has no way to say so through this handler, and that is a deliberate limit of the pattern. If a column ever needs to be cleared back to null, the handler needs a different shape, one that can tell the two cases apart.

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 PatchUser {
    pub name: Option<String>,
    pub email: Option<String>,
}

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

pub async fn patch_user(
    State(pool): State<PgPool>,
    Path(id): Path<i32>,
    Json(input): Json<PatchUser>,
) -> Result<Json<User>, AppError> {
    if let Some(name) = &input.name {
        if name.trim().is_empty() {
            return Err(AppError::ValidationError(
                "name must not be empty".to_string(),
            ));
        }
    }
    if let Some(email) = &input.email {
        if !valid_email(email) {
            return Err(AppError::ValidationError(
                "email must look like name@example.com".to_string(),
            ));
        }
    }
    let user = sqlx::query_as!(
        User,
        "UPDATE users SET name = COALESCE($1, name), email = COALESCE($2, email) 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::patch};
use handlers::patch_user;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/users/{id}", patch(patch_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 patch a user with:

curl -X PATCH http://127.0.0.1:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Asha Rao"}'

Summary

A PATCH handler is a PUT handler with one idea added: absence means keep. The input struct says it with Option fields, the validation says it by checking only what arrived, and the SQL says it with COALESCE, which falls back to the stored value when the placeholder is null. The rest of the handler is unchanged: the id comes from the path, the missing row becomes a 404 through fetch_one, and the updated row comes back with a 200.

The decision to carry forward is the choice between the two verbs, and it turns on what the client knows. A client that knows the whole new record sends a PUT with required fields, and the server replaces everything. A client that knows one change sends a PATCH with optional fields, and the server keeps the rest. The SQL differs by the COALESCE fallback, the struct differs by the Option wrapper, and nothing else in the handler needs to change. When the verb matches the knowledge, the client never has to read a row before writing it, and the server never has to guess what the client meant.