Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose enum values in a REST API

In a mobility context of use of the API, an advanced research proposes several dynamic filters that must be returned by the server. (We don't want to make too many exchange with server to initialize our filters)

In a REST api, how to expose a enum of possible values ​​for filter search?

Thank you for your suggestions/ideas?

like image 527
vincentLg Avatar asked Sep 17 '14 13:09

vincentLg


People also ask

Can we pass enum in JSON?

By default, enum values are serialized to JSON as integers. In some cases this could result in undesired behavior. If an enum is modified or re-ordered after data has been serialized to JSON, the later de-serialized JSON data may be undefined or a different enum value than was originally intended.

What is enum in REST API?

Enums, or enumerated types, are variable types that have a limited set of possible values. Enums are popular in API design, as they are often seen as a simple way to communicate a limited set of possible values for a given property. However, enums come with some challenges that may limit or impede your API design.

Can we inherit enums?

Inheritance Is Not Allowed for Enums.


1 Answers

My initial thought would be to treat the search like a normal resource. In an object oriented perspective, a search can have a collection of fields which can be used to filter by. These fields can be numeric, boolean, string based, or whatever.

So, if I understand your question correctly, then I would propose doing this:

GET /search_fields

If your API have multiple type searches that can be performed, then they can be identified by an id or maybe their name, as long as it is unique, like so:

GET /searches/{search_id}/fields

which would return a collection of search fields like so:

[{
  name: 'Field1',
  type: 'boolean'
},
{
  name: 'Field2',
  type: 'number'
},
{
  name: 'Field3',
  type: 'string'
}]

or if your fields are really just simple enums then:

[{
  name: 'Field1',
  id: 1
},
{
  name: 'Field2',
  id: 2
},
{
  name: 'Field3',
  id: 3
}]

That's my suggestion. Remember, there's no one right way to expose an API.

like image 77
arjabbar Avatar answered Oct 12 '22 19:10

arjabbar