API design debate on handling empty results gains traction
A debate among tech leads has emerged over the proper HTTP response for a GET request that finds no results, such as `/orders?userId=123`. The discussion highlights a common design tension between returning a `404 Not Found` status versus a `200 OK` with an empty array, sparking conversations about API standards and business logic.
- The core of the debate distinguishes between a resource that *is* a collection versus a specific resource that doesn't exist. For a query on a collection like `/orders?userId=123`, the collection `/orders` exists, even if it's empty for that user, making `200 OK` with an empty array a logical success response. In contrast, a request for a specific, non-existent item like `/orders/999` would correctly receive a `404 Not Found`. - Returning a `404 Not Found` for an empty collection can be misleading for developers, as it's indistinguishable from a mistyped URL or a non-existent endpoint. This ambiguity can complicate client-side logic, forcing developers to question if the endpoint itself is invalid rather than understanding the result set is simply empty. - An alternative, `204 No Content`, is sometimes proposed because it indicates a successful request with no body to return. However, the HTTP specification states a `204` response MUST NOT include a message-body, which can force clients to handle this response differently than a `200 OK` that consistently returns a JSON array, even if empty. - From a client implementation perspective, receiving a `200 OK` with an empty array (`[]`) is often preferred as it allows for consistent parsing logic. The same code that iterates over a list of results can handle an empty list without needing special checks for different HTTP status codes or null responses. - The principle of least surprise suggests an API should behave in a predictable and consistent manner. Returning an empty list as a successful `200 OK` response aligns with how many programming languages and libraries handle empty collections, which is a more intuitive outcome than an error status. - The debate also touches on idempotency, particularly for `DELETE` requests. Always returning a `200 OK` (or `204 No Content`) even if a resource didn't exist to be deleted simplifies client logic for retries, as the desired state—the absence of the resource—is achieved regardless.