Alon1980
Alon1980

Reputation: 1267

Passing enum value in restfull api

I have this scenario at hand:

  1. I have an API server holding enum value and sending it using Restfull API.
  2. The client will receive it and needs to act according to the value.

My main question: Which is better - sending the int value or the string? I can see benefits for both approaches.

Is there any way to avoid holding the enum in both sides? I am not familiar with one that actually can be useful.

Thanks!

Upvotes: 0

Views: 2022

Answers (1)

morsor
morsor

Reputation: 1323

If the API server maintains the enum, the client could fetch it by:

GET /enums

... which will return a list of enum values:

[
  { "id" : "1001", "value" : "enum-item-1" },
  { "id" : "1002", "value" : "enum-item-2" },
  ...
  { "id" : "100N", "value" : "enum-item-3" },
]

Thus allowing the client to fetch one of the enum items:

GET /enums/1017

Or perhaps perform an operation on it:

POST /enums/1017/disable

Normally, one would only refer to the enum items by their unique ID - and if the client always starts by querying the server for the enum list, you will not need to maintain the enum on the client and server.

But - if the values in your business case are permanently unique and there is a compelling reason to have 'nicer' human-readable URLs, one could use:

GET /enums/enum-item-26

Generally, this is not best practice, as the enum item value probably has business meaning and thus might change. Even though that currently seems unlikely.

Upvotes: 1

Related Questions