I'm currently designing a REST api with ASP.NET Web API.
I want to provide methods like these (http methods are irrelevant - should work for all):
- /api/client
- /api/client/CID1234 (CID1234 = Id)
- /api/client/CID1234/orders (orders = action)
The problem is: Id should be optional - /api/client may return a list of clients Action should be optional too - in one case I want to get a specific client and in the other case I want to perform a certain action on that client. (RPC style)
I don't think I can use constraints because the "IDs" I am using look very different.
This approach didn't work:
config.Routes.MapHttpRoute(
name: "RpcStyleApi",
routeTemplate: "rest/{controller}/{action}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
This approach didn't work neither:
config.Routes.MapHttpRoute(
name: "RpcStyleApi",
routeTemplate: "rest/{controller}/{action}"
);
config.Routes.MapHttpRoute(
name: "RpcStyleApi2",
routeTemplate: "rest/{controller}/{id}/{action}",
defaults: new { action = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "rest/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
This for example returns 404s because it cannot distinguish an "action" from an "id". "No action was found on the controller 'Client' that matches the name 'CID1234'.
To gain the flexibility I need should I go for a custom Actionselector? Or is it somehow possible using the Web API built in functionality? I understand that someone might want to use orders as a separate entity. But I might as well have real "actions" (not "entities") there. Like "lostpassword", "changepassword" and so forth..
Thank you for your advice
P.S.: Something like described here is not exactly something I'd be willing to do. Bad api design.