I have a situation where people consuming our API will need to do a partial update in my resource. I understand that the HTTP clearly specifies that this is a PATCH operation, even though people on our side are used to send a PUT request for this and that's how the legacy code is built.
For exemplification, imagine the simple following struct:
type Person struct {
Name string
Age int
Address string
}
On a POST request, I will provide a payload with all three values (Name, Age, Address) and validate them accordingly on my Golang backend. Simple.
On a PUT/PATCH request though, we know that, for instance, a name
never changes. But say I would like to change the age
, then I would simply send a JSON payload containing the new age
:
PUT /person/1 {age:30}
Now to my real question:
What is the best practice to prevent name
from being used/updated intentionally or unintentionally modified in case a consumer of our API send a JSON payload containing the name
field?
Example:
PUT /person/1 {name:"New Name", age:35}
Possible solutions I thought of, but I don't actually like them, are:
On my
validator
method, I would either forcibly remove the unwanted fieldname
OR respond with an error message saying thatname
is not allowed.Create a DTO object/struct that would be pretty much an extension of my
Person
struct and then unmarshall my JSON payload into it, for instancetype PersonPut struct { Age int Address string }
In my opinion this would add needless extra code and logic to abstract the problem, however I don't see any other elegant solution.
I honestly don't like those two approaches and I would like to know if you guys faced the same problem and how you solved it.
Thanks!
"-"
tag, but that will also prevent you from using the same struct for response in case your response hasname
field. The question then is, where exactly do you wan to control thisstruct
. If you want to do it at the level of the handler, you could send back abad request
response in case current name is not the same as that in the struct. If you simple want to prevent an update, you could remove it right before calling the update service. – Encrinite