Code review for JSON design used for a REST API

I am writing two REST APIs which are as following:

  1. To store the weight of user identified by id
POST /user/weight/{id}
//request body
{ "weight": 125 }
  1. To get the weight of user identified by id
GET /user/weight/{id}
//response
{ "weight": 125 }

I just want to store these user weight data in memory for now:
I am using following JSON design for this.

// For POST /user/weight/21
// { "weight" : 130 }
{
    "21" : { "weight" : 130 }
}

I am using id as the key for JSON so that I can get the weight of the user by doing just data[id], the other alternative is to use array

[
    {"id" : 21 , "weight" : 130 }
]

But for this approach I need to do a linear search over the array.
My doubt is which approach is better? Am I abusing the JSON property in the first approach?
If I store this data in database in future which approach has less changes?

1 Like

If this isn’t your final design, then I wouldn’t stress out about it. It’ll change when you add a database no matter what, and you’re not going to save any time by trying to make the “best” choice at this point. An object lookup is the way I would do it for now.

Here is a sample entry from one of my mongodb database:

{
    "_id": {
        "$oid": "58509e2b734d1d378598fefe"
    },
    "userName": "admin",
    "password": "admin",
    "type": "admin"
}

You will typically look data up by object keys. IE:

mongo.connect(url, function (err, db) 
      {
      db.collection("CollectionName").findOne({ id:0001 },(err,doc)=>{ } );
     }

Hope that helps :slight_smile: