Search code examples
c#apirestapi-design

REST-API-Design with multiple Endpoints for one Resource


I'm currently designing a REST-API.

Let's say I want to GET/POST/PUT/DELETE the following object(s)

Let's say I have the following informations which I want to GET/PUT/POST/DELETE (This is just a small example. The real object has some more properties)

public class Person
{
  public int Id{get;set;}
  public string Firstname{get;set;}
  public string Lastname{get;set;}
  public DateTime Birthday{get;set;}
  public Gender Gender{get;set;}
  public string Title{get;set;}
  public Address Address{get;set;}
  public Contact[] Contacts{get;set;}
  public History[] HistoryItems{get;set;}
  public Relative[] Relatives{get;set;}
}
public class Address
{
  public string Street{get;set;}
  public string ZipCode{get;set;}
  public string City{get;set;}
  public string State{get;set;}
  public string Country{get;set;}
}
public class Contact
{
  public string Name{get;set;}
  public string Value{get;set;}
}
public class History
{
  public DateTime TimeStamp{get;set;}
  public string OldValue{get;set;}
  public string NewValue{get;set;}
  public string ChangedItemd{get;set;}
}
public class Relative
{
  public int RelativeType{get;set;}
  public Person Person{get;set;}
}

To improve the performance of the API and the Clients (the informations are displayed on several tabs inside a TabControl. So only the currently displayed infos should be loaded) i thought about introducing more than one REST-Endpoint.

So I then would have

http://.../api/contacts/{personId} for the contacts of a person http://.../api/addresses/{personId} for the address of a person http://.../api/persons/{personId} for the "main"-informations of the person http://.../api/relatives/{personId} for the relatives to a person

This would just work fine for the GET-Request. But I think there would be a problem with the PUT/POST/DELTE-Requests. Because everything should be persisted to database inside a transaction. This (as far as i know) is not possible with multiple REST-Requests.

So what's the alternative? One "big"-Endpoint which always reads all informations from the database?


Solution

  • I think your structure is wrong, the identifer after contacts (for exemple) can not be the personId. This should be the id of the previous ressource.

    For exemple, this route: http://.../api/contacts/{personId}

    should be like that: http://.../api/persons/{personId}/contacts

    If you follow this rule, your APIs look like that:

    GET only on

    http://.../api/persons/{personId}/contacts

    http://.../api/persons/{personId}/adresses

    http://.../api/persons/{personId}/relatives

    GET/POST/PUT/DELETE on

    http://.../api/persons/{personId}