ASP.NET REST – How to Design Web API to Represent Resources

asp.netrest

I'm developing an ASP.NET Web Api 2 RESTful web api with .NET Framework 4.5.1 and C# and I'm trying to understand how to expose resources through a Web Api:

Imagine that I'm a group owner and I am the only one that can add new users to that group (I'm trying to simulate a WhatsApp group).

This is my C# class for user:

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public List<Group> Groups { get; set; }
    public List<Group> GroupsOwned { get; set; }
}

And Group class:

public class Group
{
    public int GroupId { get; set; }
    public string GroupName { get; set; }

    public User Owner { get; set; }

    public List<User> Members { get; set; }
}

How do I have to expose user's groups owned members in a RESTful Web Api?

I think I have to expose it this way:

"api/users/{ownerId}/groupsOwned/{groupId}/members/"

I will allow PUT to modify the Group to add a new member, and probably GET to get all members.

Any advice?

Best Answer

Why do you want to add the owner (which more seems like an attribute of a group) into the url? It can make sense but I don't see an argument for it. /api/groups/{groupId}/members seems to make more sense? Then you can add another path: /api/users/1/groups and /api/users/1/groupsOwned where you show a collection of links to the normal groups urls.

Because I need to pass the ID for the user that is modifying the group. If the user is the owner, he can add more members to the group.

In general that sounds as security and should be fixed by headers (like basic Auth, OAuth etcetera). It does not change which resource you show. Even better: When the owner of a group changes all urls would be invalid which is not restful. So I would suggest to leave them away and make it an attribute.

Interesting to read when you try to work restful is the concept the author of it has: Roy Fielding is the inventor of the REST concept and you can find some basics about the real concept here:

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

Related Topic