'Which is better practice in Rest API, to return NESTED empty objects (no data), first level empty object or null or 404?

For instance: Considering type Person = {id: number; name:string; age: number; description?: {eyes: string } } Considering user: Person we call the endpoint GET host/user/1

Scenario 1: user with id = 1 doesnt exist:

  • response1:

{id: null, name: null, age: null, description: {eyes: null}}

  • response2:

{}

  • response3:

null

  • response4:

http no-data code (404, 204)

Scenario 2: user with id = 1 DOES exist without optional attribute description:

  1. response1:

{id: 1, name: "a name", age: 20 , description: {eyes: null}}

  1. response2:

{id: 1, name: "a name", age: 20 , description: {}}

  1. response3:

{id: 1, name: "a name", age: 20 , description: null}

In my opinion falsy values (or the 404/204 in the first scenario) would be the best for empty attributes as they are easier and cleaner to handle.

Note: I found several similiar questions in StackOverflow but none of then with nested objects



Solution 1:[1]

HTTP status code is determined by what kind of response you are sending; are you sending an error message that tells the client that there is currently no representation of the resource? etc.

For some resources, it does make sense that the resource has a current representation even though there is no corresponding data entity in storage. That's largely going to be determined by the semantics of the resource.

If you are sending back a representation of the resource, then the handling of missing optional attributes is largely a question of schema design; omitting a name, including a name with a null value, including a name with an empty array or object are all perfectly reasonable choices for representing that information isn't available.

The fact that you are using a "REST API" to fetch a representation expressed in this schema really doesn't change the answers at all.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VoiceOfUnreason