iain
iain

Reputation: 39

Specify a number of items or all items in REST API request

I am designing an API and am wondering the best practice for values that can either specify a number or a list of items, or just specify that it is 'all' of those items.

For example imagine an endpoint /analyze that allows you to analyaze a document for specific categories. A sample request might be:

{
   "documentId": "my-doc",
   "numberOfLines": 100,
   "categories": ["category1", "category2"]
}

What would be the best way to signify that I want all lines and all categories? Have multiple types for the same value like this seems like a bad pattern:

{
    "documentId": "my-doc",
    "numberOfLines": "all",
    "categories": "all"
}

Is it best to have something like null or -1 signify all. I don't like this because it could cause errors if that logic is missed by the handler:

{
    "documentId": "my-doc",
    "numberOfLines": null, //null to mean all
    "categories": null // null to mean all
}

Upvotes: 0

Views: 551

Answers (2)

Evert
Evert

Reputation: 99728

I don't think there's anything wrong with using the string all here. Type systems like Typescript, and validation systems like JSON Schema can easily express this, and it's way more descriptive than an empty array, -1, or null.

Using codes like -1 is a bit of a leftover from earlier times when saving a few bytes was important, but it's hard to tell by eying it what it could mean. One alternative that's also fairly obvious is asterisk *.

Upvotes: 1

Andrzej Wilkoszewski
Andrzej Wilkoszewski

Reputation: 116

It depends on what behaviour you want to encourage. If expected default behaviour is to fetch all with just a possibility to filter I would make these parameter optional - i.e.

{
   "documentId": "my-doc",
}

Would be valid request, and would work the same as

{
   "documentId": "my-doc",
   "numberOfLines": null, //null to mean all
   "categories": null // null to mean all
}

On the other hand if you want clients to restrict payload by default with only only special use cases where someone might want all data IMHO it's file to introduce "magic words" e.g.

{
   "documentId": "my-doc",
   "numberOfLines": "IReallyReallyWantAllData",
   "categories": "IReallyReallyWantAllData"
}

Upvotes: 0

Related Questions