Example handle patch request using axum

I'm looking for example to handle patch request using Axum but cannot find it.
basically I want to update partial struct data
ex:

struct UserProfile {
    first_name: Option<String>,
    last_name: Option<String>,
}

so then I can send request patch to the API by update only one field or both fields

You can use the axum::routing::patch function, just like you would use get or post.

Hi, let me clarify the problem.

#[derive(Debug, Deserialize)]
pub struct ProfileChange {
    first_name: Option<Option<String>>,
    last_name: Option<Option<String>>,
}

pub async fn edit_user(
    DatabaseConnection(conn): DatabaseConnection,
    Path(user_id): Path<String>,
    Json(payload): Json<ProfileChange>,
) -> Result<impl IntoResponse> {
    println!("Payload {:?}", payload);
    Ok("Ok")
}

so when I send Patch to the API with data
{"first_name": null}

the payload output is

ProfileChange { first_name: None, last_name: None }

I need value like below so, I know which field that need to be updated

ProfileChange { first_name: None}

Ah, the problem is how to distinguish between a missing field and an explicitly provided null then. Here is a possible solution:

Thanks , I think I have found documentation about it serde_with::rust::double_option - Rust

1 Like

I've also seen a specific enum for missing, present but null and present with a value.

Here it is: optional field

1 Like

I use this one all the time for that.

interesting crate. Thanks!

I also prefer the use of discriminated unions for describing the set of operations that can be performed to patch an entity.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.