API Patterns and Practices – How to Represent Enum Types in a Public API

apienumpatterns-and-practices

I am working on a simple API that I want to use for my own client, and to open to the public in the future.
I have "Item" objects which can have different "types". The type is a C "typedef enum", for the moment I have :

typedef enum {
    ItemTypeBool,
    ItemTypeNumber,
    ItemTypeDate,
} ItemType;

(I may add some in the future)

I am wondering if I should rather transfer it as integers or as defined "strings". The JSON would be :

For integers :

{
  "name": "The name",
  "type": 0,
   ...
}

For strings :

{
  "name": "The name"
  "type": "boolean"
   ...
}

I'm wondering if there's a best practice for this. Keeping the integer would slightly simplify the code, and reduce the bandwidth, but strings would be easier for developers to remember. I remember I worked on a project, and I had to remember 1=image, 2=audio, 3=html,… which doesn't make any real sense.

So I'm asking you, if you know any other aspect I should consider.

Best Answer

Provide the strings. Numbers are meaningless. You don't use them in your own code, right (you're wrapping enum values around, that are basically strings) - why punish the user with having to use these numbers?

The only pro if you do expose the numbers - easier for you to parse these. But hey, who cares about you. Take care of the API clients.

If you provide the strings - easier for the clients; won't ever have to say things like "4 had been deprecated in favor of 17"; slightly harder parsing on your behalf, but that's fine.

Do not provide both: as a user, i'm left to wonder

  • which one do I use? Both? [on to reading docs]
  • why are there two ways to say the same thing? are they subtly different? [on to reading docs]
  • what if I specify both and there's a mismatch? will it complain? will one take precedence? which one? [on to reading docs]

As you can see, you're having me read a lot of docs for no reason.