C# ASP.NET – How to Implement a Tricky REST API with ASP.NET Web API

asp.netcnetrest

I'm trying to build a RESTful API using ASP.NET Web API for a game, and here are the methods I have so far:

/games GET
/games/:id GET
/games POST
/games PUT
/games DELETE
/users GET
/users/:id GET
/users/:id/games GET  (fetch user's games)
/users POST
/users PUT
/users DELETE

I have two questions:

  1. Where would I place the /users/:id/games method? I have two controllers (GamesController.cs and UsersController.cs). The resource I'm requesting is games, so should it go in the GamesController and pass the userid as a parameter, and I would just map it to the /users/:id/game route?

  2. Though I have a method that returns a bunch of games (/games GET), I actually wouldn't be using that at least initially. I will instead be displaying only 1 game at a time to the user, and this game will be a "popular/hot" game where there is a lot of activity and the user can also take some action (there are other games where the user cannot do any action and has to wait for action from the opponent). I can have a method called GetHotGame() that will determine which game to show to the user, when the user clicks "Next", but what I'm wondering is what the REST method should be?

Could I just use the /games/:id endpoint and pass in "hot" as the id and use the GetHotGame method to decide which game to return to the user? Or should I be using the /games endpoint and pass in "hot" as a querystring and implement a sort of paging where the page count is just one? Or, should I have a separate endpoint altogether, something like games/hot or /hotgame?

Best Answer

First, an alternative to consider...

After many years of designing and implementing web services (and inheriting some rather sub-par implementations as well), I've reached a conclusion that some others have as well: Avoid nested resource paths.

Matthew Beale's Suggested REST API Practices article explains the reasoning behind this. (Look in the First-class Models section.)

But if you insist...

  1. If you have to (or prefer to) use nested resource paths, I would suggest grouping methods based on what type of resource they return. So /users/:id/games would be implemented in GamesController. My reasoning here is that it maintains a more consistent correlation between API classes and DAL classes, which helps avoid guesswork later on, and reduces the number of inter-class dependencies.

  2. I think your querystring suggestion is the cleanest, basically for the same reasons as #1 (it returns a game, so it should be under the /games resource, and implemented in GamesController). Something like /games?keyword=hot&limit=1 resembles the pattern of successful, intuitive API approaches I've seen used elsewhere.

Related Topic