Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API Best practice ? return Empty object vs no object

let's say i have an API that returns users wallet balance and List of wallet transactions which is going to expiry

response = {
   user_balance: 20
   expiring_credits : [
     {object 1 }
     {object 2}
   ]
}

in case if user dont have any expiring transactions we can format respose in 2 ways option 1

 response = {
   user_balance: 20
 }

option 2

  response = {
    user_balance: 20
    expiring_credits : []
  }

which is the ideal option or best practices? and why? looking for some expert insights. many thanks.

like image 945
maaz Avatar asked Apr 25 '21 10:04

maaz


2 Answers

Your returned data should reflect the shape of the data being asked for. If they're asking for a user's information, and that includes a user balance as one-to-one and expiring credits as a one-to-many, you should include those relationships. If there is nothing to be included, specifically call it out with a null if it's a one to one to let the dev know "there is a lack of data here" and if it is a one to many, return an empty array, as there were no dependant records but there was a master record.

An example endpoint:

/user/[id]/credits
GET
id: the user's id
{
  user_balance: null | number, // o:o
  expiring_credits: credits[] // o:m
}

This way the data shape is always the same for the consuming developer and they would not have to worry about top-level keys no existing on the returned object. It'll always be there, and it will always be consistent with the type returned.

If it exists, it will be this type. If it would be an array, it will always be an array. This lets people code to the data shape, not to the possibility of the data shape.

like image 95
Robert Mennell Avatar answered Oct 10 '22 03:10

Robert Mennell


which is the ideal option or best practices?

REST doesn't care.


What you have here is a question about schema design, and specifically whether or not your expiring credits field should be optional or mandatory.

For instance, OpenApi uses optional parameters by default; your specification must explicitly "opt-in" to using required parameters (the "required" field is optional). This pattern holds for objects in your schema, just as it does for parameters in your URI (the "required" field is optional).

The choice between optional vs mandatory can impact you later if you discover that you need to modify the schema, and want to do so in a way that doesn't break existing clients. The XML community explored this question back in the day, so you will want to look into their conclusions (and in particular policies like must-ignore and must-forward).

like image 37
VoiceOfUnreason Avatar answered Oct 10 '22 02:10

VoiceOfUnreason