The main focus of this article is on how to make Web APIs more understandable to consumers from a Resource URI construction point of view.
In Web API, each resource has a unique identifier. So, one should be very careful while constructing these URIs. Here are a few very good practices one should go for:
URI should belong to NOUN rather than ACTIONS.
URI example | Is preferred? | Remarks |
api/getemployees | × |
api/employees | √ | Use GET |
api/id/employees | × |
api/employees/{id} | √ | Fetch employee with a given ID |
api/xyz/xyz/employees | × |
api/employees | √ |
api/employees/orderby/name | × |
api/employees?orderby=name | √ | Filter criteria |
Should a noun be pluralized or not?
It is up to you whether you want to pluralize nouns or not. But whatever decision you are making, it should be consistent throughout the controllers and actions.
Should ids be integer or string?
One point to remember here is that the resource URI construction has nothing to do with the way data is stored at the back-end. REST API has nothing to do with data storage mechanisms. In other words, if the back-end is changing over time, the URI must not change. For example, today you are using a SQL Server database with auto-incremented integer key as an ID. Now, what if I suddenly planned to move to Mongo DB? Would I go ahead to change my URIs to accommodate ID as a string? Certainly not. The best solution for this is GUID. GUID can be used as a primary key in any database, which will provide more flexibility while changing the backend database, keeping the resource URI intact. GUID will also help us to hide underlying technology.
Disclaimer
All the points mentioned above are just the guidelines and by following these, we can end up with good URI design.