Search code examples
apirestpostapi-design

Array vs hashmap in the request body of a (POST) rest API


I'm building an application that involves a frontend (javascript browser-based client) and a backend (a Java-based service).

For one of the APIs (POST method) that will be called from the browser to the backend service (upon filling a form in the frontend), I'm planning on passing the request body (JSON) as follows

{
    data: [
        {
            "fieldId": "123sda121231",
            "fieldValue": "some_user_input_for_field_1",
        },
        {
            "fieldId": "223sda121231",
            "fieldValue": "some_user_input_for_field_2",
        },
        {
            "fieldId": "323sda121231",
            "fieldValue": "some_user_input_for_field_3",
        }
    ]
}

However, now I'm confused and I'm wondering if I should probably do it the following way.

{
    data: {
        "123sda121231": "some_user_input_for_field_1",
        "223sda121231": "some_user_input_for_field_2",
        "323sda121231": "some_user_input_for_field_3"
    }
}

Can someone help me understand which would probably be the better way to structure this request body?

P.S. FieldIds are predefined in the backend.


Solution

  • Usually, in design problems, there is no single correct answer, a solution can be good for one problem and it can be bad for another problem.

    I prefer the approach of creating an array of Object ( lets call our class as FieldData). In above example, FieldData class is:

    public class FieldData{
       String fieldId;
       String fieldValue;
    }
    

    The benefits I see with this approach:

    1. The response is very flexible, in future we can easily add one more field in the FieldData object without breaking the API contract.
    2. The response sent is easier for the client to understand, the client will know that fieldId contains the id of the field and fieldValue contains its value. Whereas in the case of a map this logic is not explicitly available.