Question

I have been looking at routing in the Web.Api and looking at various ways of representing endpoints. I came across Instagrams REST endpoints. (which has some lovely documentation) Using the Web.Api what would be the best way to set up the routing and controllers for a sitution like Instagrams user endpoints?

User Endpoints
GET/users/user-id                  Get basic information about a user.
GET/users/self/feed                See the authenticated user's feed.
GET/users/user-id/media/recent     Get the most recent media published by a user.
GET/users/self/media/liked         See the authenticated user's list of liked media.
GET/users/search                   Search for a user by name.

If I wanted to replicate these endpoints in my app, how would I go about it. Would I just need one controller 'Users' with 5 methods, what kind of routing would I need to direct the REST calls to those methods?

Was it helpful?

Solution

I would structure this in a different way.

GET/user
GET/user/user-id
GET/user?q=user-name

GET/media
GET/media/user-id
GET/media/user-id?selection=recent
GET/media/user-id?selection=liked

GET/feed
GET/feed/user-id

This way you keep your Controllers for a specific target, much like keeping your classes for a single responsibility.

  • User
  • Media
  • Feed

When you use this approach it's much easier for a user to 'guess' the path. And I think you could already guess what each path does without any explanation. For me that's the most important when I'm designing a API.

GET/controller            - always returns a item list
GET/controller/id         - always returns a specific item
GET/controller?q=         - always queries the controller
GET/controller?selection= - always selects a subset from the list off items

Ofcourse this is open for interpretation but it gives you an idea about how I would solve this particular problem and maybe some ideas to think about. Also have a look at this great book from Apigee - Web Api Designs

http://info.apigee.com/Portals/62317/docs/web%20api.pdf

Edit:

To make the routes you named I think you've got 2 (not very ideal) options.

  1. Map a specific route for each url
  2. Make a wildcard route

Option 1 I have not tried, or used this myself but you can find more info here:

Single controller with multiple GET methods in ASP.NET Web API

Option 2 If you go the wildcard route all requests with additional parameters will be routed to your default Get() method. In your get you have to look at the parameters using ControllerContext.Request.RequestUri.AbsolutePath or something like it and choose your actions on it.

config.Routes.MapHttpRoute(
     name: "MyApi",
     routeTemplate: "api/{controller}/{id}/{*wildcard}",
     defaults: new { controller = "index", id = RouteParameter.Optional }
 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top