Jos Vinke
Jos Vinke

Reputation: 2714

Web Api endpoint complex object vs simple flat object best practice

What would be the best way to offer a resource in ASP.NET Web Api? Are their any references or guidelines for this?

Lets say for example we have a person.

Option 1:

{
  "Personalia": {
    "CitizenServiceNumber": "23443342",
    "FirstName": "John",
    "LastName": "Web",
    "Gender": "Male",
    "DateOfBirth": "1965-02-16",
  },
  "Spouse": {
    "FirstName": "Emily",
    "LastName": "Web",
    "Gender": "Female",
    "DateOfBirth": "1968-02-16"
  },
  "Address": {
    "HouseNumber": "565",
    "Street": "Somewherestreet"
  }
}

Option 2:

{
    "CitizenServiceNumber": "23443342",
    "FirstName": "John",
    "LastName": "Web",
    "Gender": "Male",
    "DateOfBirth": "1965-02-16",
    "SpouseFirstName": "Emily",
    "SpouseLastName": "Web",
    "SpouseGender": "Female",
    "SpouseDateOfBirth": "1968-02-16",
    "HouseNumber": "565",
    "Street": "Somewherestreet"
}

This is ofcourse a fairly simple example but the question remains the same with a more complex class.

Upvotes: 2

Views: 1097

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039248

I would go with the first option. You shouldn't be worried about having lots of objects. Those are called view models and are used exactly for this purpose. In addition to that you could reuse some parts of those objects in other parts of your API where you might need things like addresses, persons, ...

If you look more carefully at this JSON string you don't actually need Person, Personalia and Spouse objects to map this structure. A single Person object would be enough.

For example here's how the view model that your API controller action takes might look like:

public class MyViewModel
{
    public PersonViewModel Personalia { get; set; }
    public PersonViewModel Spouse { get; set; }
    public AddressViewModel Address { get; set; }
}

Upvotes: 3

Related Questions