I have a Web Application for which we are adding an API now.
I am looking for best practices to keep in mind while working on this.
I am considering these factors:
DRY: Avoid redundancy (to the extent possible). Take for example, a part of the code which handles a form submission. There are some parts which are applicable for only Web Form submission but not relevant to the equivalent API Post call. I am thinking of modularizing the common code behind this Post handlers. I must add that the handler classes for Web Form and API are different. I am creating a third class which will have the common methods. This third class would be inherited by the two handler classes (along with their other base classes, multiple-inheritance).
Should I refactor the code such that the Web Form 'Post' handler method in turn calls the API Post method?
Thanks.
I think the specifics of this will vary significantly on a case by case basis, but I did something like this recently, and I'll share what I came up with.
This is how I organized my handlers so I don't repeat myself:
I added a lot of utility methods that can be used by subclasses. For example,
MyHandler
has awrite_json
method because that is used in a lot of places, andApiHandler
has aprocess_json
method because that is used only by APIs.I think it is a bad idea to avoid repeating yourself by having one post method call another post method. Instead, I think it would keep your code cleaner to do the refactoring at the model level.