1

What’s the recommended design for an endpoint that accepts a nested resource as the following:

POST /account

{
    "name": "Project John Doe",
    "description": "Description of the account...",
    "type": "corporate",
    "relation_number": "PR2022-1509-8",
    "contacts": [
        {
            "firstname": "John",
            "insertion": "",
            "lastname": "Doe",
            "email": "john.doe@example.com",
            "phone_mobile": "1234567890",
            "phone_steady": null,
            "street": "Foo Street",
            "building_number": "12-A",
            "postal_code": "123456AB",
            "city": "Foobar",
            "country": 19,
            "priority_level": 1
        }
    ]
}

The requirement is that when an account is created, at least one account contact person must be present.

There are two common options, but I wonder which one should be used:

  1. Creating one endpoint that accepts a POST request containg the JSON as shown above. Thus, accepting a nested object.

  2. Creating two endpoints, POST /account and POST /account/contact
    The client is responsible for creating an account in one request, and then create a contact person using a second request. Some sources on the internet suggest to take this approach.
    But, when a client just doesn’t/couldn’t send that second POST request to create a contact person for the just created account, the data is inconsistent.

How should this be designed to comply with the guidelines?

4

1

The problem isn’t so much which one to choose but that the two solutions conflict.

ie. if I post to account with the contact list then I overwrite (possibly delete entirely?) the relationship with existing contacts which may have changed since I got my copy of account.

My advice would be to avoid the nested object and represent the relationship with just IDs. eg

account
{
    "Id": "a"
    "name": "Project John Doe",
    "description": "Description of the account...",
    "type": "corporate",
    "relation_number": "PR2022-1509-8",
}

contact
{
    "Id": "b"
    "AccountId":"a"
}

Now as long as I accept non existing account ids on Contact, I can upsert both account and contact to their own endpoints, following whatever RESTful URLs and methods you feel best.

Plus you can get big lists of accounts without sending all the unneeded contacts.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *