Home > database >  Is good practice with REST APIs to assume default values when values are not present?
Is good practice with REST APIs to assume default values when values are not present?

Time:11-29

An application let others applications to get weather information for a region. This application implements a REST API and JSON objects to represent the resources and the users indicates the region via region attribute in a JSON object in the request.

It is working this way: if the region is not indicated in the request, this is if the attribute is not present in the JSON or it has null value, the application assumes region is "Tenesse" (some region by default). Is this a good practice? What is the disadvantage of doing this against making the region a required attribute and explicitly indicates the region?

CodePudding user response:

I comes with this incoveniences of not doing explicit the region value in the request: If an error at the user (a user is an application here) side makes the user to not send the region at all, this user can maybe be consulting the weather thinking its it about other region. So making the value explicit make sure that this kind of errors are not masked while the user assumes it is consulting weather for another region.

CodePudding user response:

Is this a good practice?

It's fine.

Creating "required" fields when introducing a new message is straight forward.

Introducing "required" fields to an already published schema is a mess, because you already have lots of producers/consumers running out in the wild that all need to be changed.

In the case where the existing schema necessarily implies the same value for this new field, introducing an optional field with a default allows you to extend the meaning of the messages to cover new regions with breaking existing implementations.

Imagine a message describing an address. Today, all addresses of interest are located on "Earth"; making that explicit by adding a "planet" field is a waste of everyone's time. But years from now, when we start collecting addresses from other planets? we'll need that field. Making it an optional value with a default of "Earth" allows us to include the new business cases without breaking any of the existing implementations.

David Orchard wrote about these concerns for XML documents; Extensibility, XML Vocabularies, and XML Schema might be a good introduction.

  • Related