Neil Thompson
Neil Thompson

Reputation: 6425

Asp.NET WebApi Convention based approach Url/Route query

I'm not sure of the 'best practice' way forward for an asp.net webapi convention based rest service that needs to return a 'sub property' of a resource.

eg:

UsersController

public User Get(int id) { ... } //returns named user via /api/v1/Users/23

but if I want to return a given users role collection I think I'd like a url of /api/v1/Users/23/Roles

If you were using my api would you consider this acceptable?

If it is acceptable, what would my routeTemplate and method signature look like (sorry if this is obvious - I've really confused myself today)

All the web api examples I can find are too simple and just use DELETE,PUT,POST and two GET's - none seem to cover anything like sub properties (as above) or Partial Responses /api/v1/Users/23?fields=id,name - If anybody knows of a good example out there that would be awesome.

Many Thanks

Upvotes: 3

Views: 1316

Answers (1)

Mark Jones
Mark Jones

Reputation: 12194

Roles

Roles looks like a very sensible sub resource.

Assuming you will want to list and remove roles from the user using http verbs... then you can use two controllers, one for Users and another for Roles. Your routes would then look like so:

config.Routes.MapHttpRoute(
            name: "UserApi",
            routeTemplate: "api/v1/Users/{userId}/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Your roles controller would then have methods like:

public class RolesController : ApiController
{
    // GET api/v1/users/1/roles
    public IEnumerable<Role> Get(int userId)
    {
        //
    }

    // GET api/v1/users/1/roles/1
    public IEnumerable<Role> Get(int userId, int id)
    {
        //
    }

}

Roles as a partial response of User

For what formats and standard to use for the request:

apigee do a free eBook on their site where they make design recommendation's and observations about existing API's.

They describe partial response examples from LinkedIn, Facebook and Google. It is covered in one of their blogs here and in their book here.

How with WebApi ASP.NET

Assuming the use of JSON as the content type, then a similar question has been asked before ASP.NET Web API partial response Json serialization, in short you will need to pass the query param for "?Fields=" or such like into a custom ContractResolver.

Upvotes: 2

Related Questions