Asp.NET WebApi Consistent Url / Route query approach

I'm not sure what the best practice path will be for an asp.net webapi based breakout service that should return the "sub property" of the resource.

eg:

UsersController

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

      

but if i want to return a specific collection of user roles i think i need the url /api/v1/Users/23/Roles

If you were using my api would you find it acceptable?

If that's acceptable, then what my routeTemplate and method signature looks like (sorry if it's obvious - I really confused myself today)

All the web api examples I can find are too simple and just use DELETE, PUT, POST and two GETs. None of these seem to have anything like sub properties (as stated above) or Partial Responses /api/v1/Users/23?fields=id,name

- if anyone knows of a good example that would be awesome.

Many thanks

+3


source to share


1 answer


Roles

Roles seem like a very sensible helper resource.

Assuming you will need to display and remove roles from a user using http verbs ... then you can use two controllers, one for Users and the other for Roles. Then your routes will look like this:

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 }
        );

      

The role controller will 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 partial user response

For which formats and standards to use for the request:

apigee makes a free e-book on their site where they make design guidelines and observations of existing APIs.

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

As with ASPA ASP.NET

Assuming using JSON as content type, asked a similar question before the Json partial response for ASP.NET Web API , in short, you will need to pass the request parameter for "? Fields =" or similar to the custom one ContractResolver

.

+2


source







All Articles