For example, let's say that I have an endpoint to get a list of buildings, that can be either apartment or house. The client can filter by apartment or house. Apartment has a property floor
that house doesn't have, so floor
will be null for all houses. For a response with a list of houses we would have
{
[
{
"address": "1, foo street",
"size": 400,
"floor": null
},
{
"address": "2, bar street",
"size": 500,
"floor": null
},
}
We can also have apartments and houses in the same response, but floor will always be null for houses.
Can I remove the floor field for houses or would that be a bad practice?
3 Answers 3
In my experience is totally fine to return different building type as long as the client agrees on this "contract" and is able to process them as they are.
Usually having an explicit type field indicating what kind of building is the current one helps the consumer to identify the object and process it accordingly. This is prefered over something not so explicit as "when field x is null it means y"
Document what you will be sending. If you want to make client side developers happy, create an endpoint that describes what you will be sending.
Only send null fields if there is a difference between a field being null and a field not being present, and document the difference. I have to handle the case of a field not being present anyway. So I expect a null field to have some significance.
It's fine.
There're some REST APIs which play with the capacity to select fields. See OData.
These APIs are interesting when your resources are not strictly typed, or collections are heterogeneous data sets (a mix-up of resources).
In any case, I agree with @gnasher729. Documentation is highly appreciated. A widespread standard for documentation is OpenAPI.
Additionally, you can also check Json Schema. While its goal differs from the OpenAPI one, it's still documentation any developer should understand.
/list
and requests to a house-specific endpoint like/list/houses
:/list
responses should not change depending on the contents of the response, while/list/houses/
responses never have any reason to includefloor
."type": "apartment"
that makes it possible to tell which fields can be expected.