Let's say we have an api enpoint to deal with a superhero resource:
api/superheroes POST
- to create a heroapi/superheroes/{id} GET
- to fetch a hero
The resource model is the following:
public class SuperHero
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Now a Product Owners say they'd like to introduce superhero teams. As of now a given team has a name and at least one hero attached. I can see two options to proceed with.
1) Straightforward
Introduce a new resource:
api/teams POST - creates a team
And the resource model will look like the following:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<int> SuperHeroes { get; set; }
}
In such a way api users will send a single request to create a team. A list of superheroes must be specified and be non-empty
2) Revisit requirements
What does
team has a name and at least one hero attached
actually mean? Well, having no heroes the team is definetely not ready to save the world. But is it the obstacle to its existence? And do we really need to prevent users from creating a team with no heroes attached?
Let's introduce a team and attached superheroes as a resource and sub-resource respenctively:
api/teams
POST
- to create a team with a name and an empty list of memberspublic class Team { public string Id { get; set; } public string Name { get; set; } //potentially other team properties }
api/teams/superheroes
POST
- to attach heroes to a teampublic class TeamSuperhero { public string SuperheroId { get; set; } //potentially other properties related to the fact of attach itself }
My feeling is that the second approach contributes to endpoints' simplicity and responsibility separation. Also it might be better from performance perspective as fetching a team probably doesn't mean the user needs an associated superhero list. At the same time it forces api consumers to use two calls instead of a single one to create a ready-to-go team.
What additional questions should be asked here to choose the right option?