Juneyoung Oh
Juneyoung Oh

Reputation: 7652

API interface design - toggle or 2 different interfaces

I am studying interface design.

Here is what I curious about.

I question this, since it could be implemented with toggle.

i.e. user send item_id and user_id. server check database(this item is already liked or not), and update.

Thanks for answer!

Upvotes: 4

Views: 685

Answers (2)

Suever
Suever

Reputation: 65460

The real benefit to having two interfaces for toggling is that it doesn't require the user to know the current state of the thing they are attempting to change (i.e. it doesn't require me to first query for the state).

If I am a consumer of an API, typically I will want to perform actions such as like-ing something. Very rarely can I think of a case where I would want to perform the action of do the opposite of what I did previously (unless I'm feeling like flip-flopping). If you didn't have two endpoints for like and unlike then you'd first have to poll the API to get the current status, and then perform the toggle that you're talking about if needed.

This situation introduces more logic into your code, requires that you make 1-2 calls to the API, and assumes that the state didn't change between calls; whereas having two endpoints reduces the logic, limits your API calls to 1 per action, and you don't have to worry about the state changing unexpectedly.

In the case where you try to like something that the user has already liked, then the API would simply return a successful result and not alter the underlying data.

Upvotes: 4

mzulch
mzulch

Reputation: 1539

One reason to prefer an interface where you specify the desired state explicitly is that it will be idempotent. That is, the resulting state is the same even if the request is made multiple times.

This is a pretty contrived example, but if two different people sharing the same account tried to like the same thing within a small enough window, you could end up with it being un-liked instead.

Upvotes: 0

Related Questions