Search code examples
phprestserverapi-design

API - WebSite communication. Should I duplicate logic?


I have been looking for the answer for this question but it was a bit tough for me to come up with the query (question) itself. So if there is already good answer for the below question i would be very grateful for the link.

Let's assume I have an e-commerce web site and an API endpoint for future calls from mobile apps. My question is: should I duplicate logic for querying let's say product for product page on website or should I consider website as an API client and displaying product info by making CURL? request to API.

I suppose I should stick with last one. But I am concerned about making extra curl(TCP/IP) request within script. Will it be significantly slower for the overall response time? Are there any other "patterns" I am not aware of? Thank you.

Sites are on same server but API uses Phalcon PHP and website uses regular PHP


Solution

  • Duplication is definitely the wrong thing to do.

    Technically, you have three options:

    • move the shared business logic to a separate repository and reuse it in both project as private composer package
    • use cURL/socket wrapper library to access the API (probably using Guzzle)
    • make public calls to the API using JS (preferably via fetch)

    Each of these was drawbacks, so your choice would depend on which option hurts the less.

    The shared library would have the best performance, but it would complicate the deployment process and there will be situations, when those applications (site and api) will have contradicting requirements. The problems are organizational.

    Internally calling the API server over HTTP will make the site be a lot less responsive (since the TTFB will be a lot longer), but it would let you leave the API code completely unchanged.

    Having it all in public comes with security and authorization problems. But, depending on how you expect the mobile API clients to be made, this could be seen as future-investment. But it will require substantial development time and someone who is skilled with javascript (maybe even with JS frameworks), since your website would have to be heavily altered. Most development-intensive option.