Consistent API design
Suppose we have an API /getTransaction with following response
{
transactionId: “TCC1232434”,
bankName: “ABC”,
accountNumber: 12131314,
transactionComments: "comments"
}
We might have another API to create the transaction and generally, transactionComments
is an optional field
So while creating a transaction if someone does not enter transaction comments, nothing is stored in the database for field transactionComments
which is equivalent to null
and thus calling /getTransaction will return
{
transactionId: “TCC1232434”,
bankName: “ABC”,
accountNumber: 12131314,
transactionComments: null
}
Now consumer of API is expecting transactionComments
to be a string, and so might have string methods applied on transactionComments
like this transactionComments.replace(' ‘,' — ‘)
Getting null as a value for
transactionComments
from API, breaks this frontend code
We could well apply null check at front-end, but the number of places where this null check has to be applied is incalculable, so this null check should be handled by API, not frontend code
Thus a valid API response in case transactionComments
in database is null should be
{
transactionId: “TCC1232434”,
bankName: “ABC”,
accountNumber: 12131314,
transactionComments: null
}
So now when we have agreed over handling such checks at API level, we have to define a compatible null value as well
In our example ‘’ is a perfect null value for transactionComments
and for other cases, we have to find a value which is not a valid value and define it as a null value like maybe 0 for account number assuming a valid account number can never be 0
The contract between front-end and backend is not broken due to value changes in the database
Please let me know your views.