Monday, September 10, 2018

Web API Resource URI construction Practices

Main focus of this article would be on how to make Web API more understandable to the consumers from Resource URI construction point.

In Web API, each resource will have unique identifier. So, one should be very careful while constructing these URIs. Here are the 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
Using GET
api/id/employees
×

api/employees/{id}
Fetch employee with a given ID using GET
api/xyz/xyz/employees
×

api/employees

api/employees/orderby/name
×

api/employees?orderby=name
Filter criteria

Should Nouns be Pluralize or not?
It is up to you whether you want to go for pluralize nouns or not. But whatever decision you are making it should be consistent throughout the controllers and actions.

IDs should be integer or string? 
One point to remember here is, resource URI construction has nothing to do with the way data is stored at backend. REST API has nothing to do with data storage mechanisms. In other words, if backend is changing over time, URI must not change. 

For example, Today you are using SQL server database with auto incremented integer key as an ID. Now, what if I suddenly planned to move to Mongo DB. Will I go ahead and change my URIs to accommodate ID as a string? Certainly not. 

Best solution for this – 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
Please note, all the points mentioned above are just the guidelines and by following these we can end up with good URI design.

No comments:

Post a Comment