Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API PUT/PATCH to flip boolean

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?

like image 736
DerektheDev Avatar asked Jun 06 '16 20:06

DerektheDev


People also ask

Is it better to use PATCH or put?

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.

Why you shouldn't use booleans in rest APIS?

If not carefully considered, booleans can: Obstruct API Extensibility. Mask and obfuscate Domain Clarity. Hamper Code Readability and Maintainability.

What is difference between put Post and PATCH?

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.

How does PATCH work in REST API?

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.


1 Answers

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.

like image 200
Johannes Thorn Avatar answered Oct 02 '22 14:10

Johannes Thorn