Reputation: 3075
This is a design problem specific to a Web API project I'm working on, but it might be a question that's general to REST principles. It's also possible I'm completely overthinking this.
I have a class in Entity Framework that has a child collection of another class:
public abstract class Tracker
{
[Key]
public int ID { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public virtual ICollection<Unit> Units { get; set; }
}
The Unit class looks like this:
public class Unit
{
[Key]
public int ID { get; set; }
[MaxLength(50)]
public string Name { get; set; }
}
I'm working on a Web API that will GET a list of trackers, and GET a list of available units, then add a particular unit to a tracker's list of units. Trackers and Units have their own API controllers and repositories and I'm trying to figure out how to modify them to support creating this association, and what the request would look like.
Is it appropriate to update the Tracker endpoint (/Trackers/1) via PUT to add a new Unit to the list, maybe along with the existing Units? How would I handle that on the back end? I think one of the mental hurdles I have with the PUT approach is - would I include the entire child object in the request body collection property? It wouldn't make sense to, but I'm not sure how it would work otherwise. The assumption (in my case) would be that the Unit being added to the Trackers list would be one that already exists and we're just creating the association. Should I maybe use DTOs for both of these to accomplish this more simply and map them accordingly?
Or would it make more sense to create some new joint DTO like "TrackerUnit" with a corresponding endpoint that I can add new associations to by POSTing to that endpoint (POST /TrackerUnits), then handle the processing in a new controller for it? I would think it would also need to support a DELETE to remove the items. I'm not crazy about this approach since this endpoint wouldn't correspond to any actual resources in my system, but just be used for mapping these associations.
Upvotes: 3
Views: 505
Reputation: 4978
How about creating an endpoint:
/Trackers/{id}/units
and then you can Post a Unit to this endpoint to associate with the Tracker identified by the {id}, or similarly:
DELETE /Trackers/{id}/Units/{unitid}
to remove a Unit.
Upvotes: 5