开发者

Should a RESTful API return 404 for arrays of objects?

Lets say there's a Product with Orders. If you ask for /products/product_id, it will return a 404 if product_id doesn't exist. But 开发者_运维百科should /products/product_id/orders return a 404 if no orders exist for this product or should it return an empty array?


I would return an empty collection. A product with zero orders is a completely valid concept, so the existence of an empty orders collection makes more sense than a 404 which would infer that this product does not have a orders collection.


You really should do only one of two things

Either Return a 200 (OK) status code, and an empty array in the body.

Or Return a 204 (NO CONTENT) status code and NO response body.

To me, option 2 seems more technically correct and keeping in line with REST and HTTP principles.

However, option 1 seems more efficient for the client - because the client does not need extra logic to differentiate between two (success) status codes. Since it knows that it will always receive an array, it simply has to check for whether it got none, one, or many items and process it appropriately


Do not return arrays. Return an object in any case, like

{ 
   offset: 30,
   limit: 10,       
   arr: []
}

it allows you to add metadata (for pagination or smth else)

usually with http status code: 200

Also, this is conventional web API behavior, driven by security concerns: https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside


In my opinion:

We're talking http status values here, and should be of a higher level of giving responses.

One should see this in layers of delegates. Like when your api is not able to answer a request, in case the api call itself is not available, then you could reply with a 404.

But when your call exists, and it could reply with a collection of data, but its an empty collection, you could return just a http 200, with an empty result.

I would use http status values to give an indication on the request validation, and not directly make it dependent on the content in the deeper api layers.

Or one could strictly follow protocols found on the net, but nobody follows them...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜