3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. I think you have just helped me have a route matching breakthrough :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.