Whats the best way to handle optional field in PUT http request at backend

Viewed 807

I couldn't find developers guide for a PUT call. What should we do if in a PUT request an optional value is passed as null. Do we set it to null in db or we retain the previous value in db if any? The issue with this approach is we won't be able to update the values to nullify optional fields once created with value.

Eg. For the same Entity suppose Student table, I have a nullable column of name suppose student_optional_subject. Now in POST student_optional_subject is set to value "calculus". Again a PUT request is made with student_optional_subject as null in the request body(i,e the field is missing in the request as it is an optional field).. shall I retain "calculus" in student_optional_subject or set it to null..

2 Answers

If a value in a PUT request is null, it should be saved as null. It should not be ignored because it's optional.

The way the PUT method is defined, it should always be a full update of the resource. If I do a PUT and then a GET of the same resource, the representation I receive from the GET should be equivalent to representation sent in the PUT.

If you ignore null fields, that's known as a partial update. PUT does not support partial updates. This is one of the most common things people get wrong when building REST APIs.

If you want to do partial updates, you can use the PATCH method. However, be careful because PATCH is used incorrectly even more often than PUT. If you use PATCH, you should be using a diff media type such as application/patch+json or application/merge-patch+json.

If you have a Student table, there should be no reason why the name of a student should be optional. If a Student exists, it should be understandable that they have a name associated with it. Each entry in the Student table could be associated with a primary-key like id that auto increments or uuid that is a randomly generated 64/128 bit unique id. At that point you should have another table called Subject. If the PUT doesn't contain a student_subject then you don't create a new Subject row. However, if it does, create a new StudentSubject for the given Student where the association is the id or uuid. This way, students can still have subjects or no subjects, but the Student table doesn't care if they do or not.

CREATE TABLE `student` (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(128),
    PRIMARY KEY (id)
);

CREATE TABLE `subject` (
    id int(11) NOT NULL AUTO_INCREMENT
    student_id int(11)
    title varchar(64)
    PRIMARY KEY (id)
);
Related