What is the proper way to flip a boolean over a RESTful API?
Consider, for example, a users/toggle_middle_name
endpoint. By default, each user would not have his or her middle name displayed, unless they opted in by hitting an endpoint.
Obviously, this would not be a GET
endpoint, as you'd be writing information to the database. But, in a PATCH/PUT
request, it's my general understanding that one should send parameters, signifying what data is being set to. So, for example, one would send {show_middle_name: true}
. But since this is just a boolean being flipped server-side, ideally, you wouldn't need to know whether to send true
or false
prior to the call. Just hit the endpoint, and it flips from one to the other, without a value being sent.
The question then becomes, is it okay to just hit a PUT
/PATCH
endpoint without parameters, and simply return the result in a response? Or are parameter-less PUT
/PATCH
API calls discouraged? Why or why not?
When a client needs to replace an existing Resource entirely, they can use PUT. When they're doing a partial update, they can use HTTP PATCH. For instance, when updating a single field of the Resource, sending the complete Resource representation can be cumbersome and uses a lot of unnecessary bandwidth.
If not carefully considered, booleans can: Obstruct API Extensibility. Mask and obfuscate Domain Clarity. Hamper Code Readability and Maintainability.
Here is a simple description of all: POST is always for creating a resource ( does not matter if it was duplicated ) PUT is for checking if resource exists then update, else create new resource. PATCH is always for updating a resource.
The PATCH HTTP method is used to modify the values of the resource properties. The PATCH HTTP method requires a request body. The body of the request must contain representation of the JSON Patch operations that you want to perform on the resource.
Simply said: Don't
In my opinion there should be no specialized resource for flipping a boolean because a boolean in itself does not define a self contained entity.
Instead I would make this an attribute of User
and do a PATCH
on /users/john_doe
with
{
"show_middle_name": true/false
}
As the comment from jonrsharpe applies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With