Should a RESTful API return 404 for arrays of objects?

前端 未结 4 1744
旧巷少年郎
旧巷少年郎 2021-02-03 18:58

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

相关标签:
4条回答
  • 2021-02-03 19:32

    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

    0 讨论(0)
  • 2021-02-03 19:44

    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 讨论(0)
  • 2021-02-03 19:45

    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://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside

    0 讨论(0)
  • 2021-02-03 19:48

    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.

    0 讨论(0)
提交回复
热议问题