Web and API – Reusing Business Logic

Architecturesoaweb servicesweb-applications

We have a website and two mobile apps that connect through an API. All the platforms do the exactly same things. Right now the structure is the following:

  • Website. It manages models, controllers, views for the website. It also executes all background tasks. So if a user create a place, everything is executed in this code.
  • API. It manages models, controllers and return a JSON. If a user creates a place on the mobile app, the place is created here. After, we add a background task to update other fields. This background task is executed by the Website.

We are redoing everything, so it's time to improve the approach. Which is the best way to reuse the business logic so I only need to code the insert/edit/delete of the place & other actions related in just one place?

Is a service oriented approach a good idea? For example:

  • Service. It has the models and gets, adds, updates and deletes info from the DB.
  • Website. It send the info to the service, and it renders HTML.
  • API. It sends info to the service, and it returns JSON.

Some problems I have found:

  • More initial work? Not sure..
  • It can work slower. Any experience?

The benefits:

  • We only have the business logic in one place, both for web and api.
  • It's easier to scale. We can put each piece on different servers.

Other solutions

  • Duplicate the code and be careful not to forget anything (do tests!)
  • DUplicate some code but execute background tasks that updates the related fields and executes other things (emails, indexing…)

A "small" detail is we are 1.3 person in backend, for now 😉

Best Answer

I've encountered this before (many times) and what I've ended up doing preferring is:

Take the BL out of the website. Make the website a consumer of the API. Treat the website as just some other client of your API. Your API IS the service.

If you find yourself thinking that you need special API methods just for the website, think again! If its good for the goose, it is good for the gander. If you really really really need special functionality for the website I would suggest that what you've really found is a difference in "user profile" and therefore this is a situation where the API should still support the "special" functions, but then you control them via authorisation.

Not convinced?

Take the paradigm a step further ...

The phone app is running on a platform where bytecode is executed, the app lives in the phone and consumes API services via HTTP/JSON

The website is an app running on a platform where HTML+Javascript is the executed, the app lives in a the browser and consumes API services via HTTP/JSON

Same same!

Extend that to tablets, TVs, other phone platforms, plugins, third party apps, mashups, ...

Lots of different user experiences all plugged into a common API.

Your app IS the API. The website is just one client (of many)