1

The PHP framework Laravel allows to make an API and a website on the same application. As both of them will communicate with the same database, I was asking myself what is better between consuming my own API for my website and making a DAO proper to the website.

On one hand, consuming my own API would make a single entry point to the database for all the application, and it would allow to make dynamic pages, but on the other hand it requires a lot of javascript for internal requests and DOM queries, and it is harder to make certain routes accessible only for admins for example.

What do you suggest?

I'm merely taking Laravel as an example, it could be any other web framework.

Thank you for your help.

  • 1
    You write an API and consume it when you have multiple frontends, i.e. a web page, a mobile app and a desktop application. – Robert Harvey May 29 '18 at 21:17
  • But is it always the case? For example if I want to make a back-office website for the administrator, isn't it better to separate the API and the website so that I can check easily if the authenticated user is admin, instead of writing middlewares for API's routes? – JacopoStanchi May 29 '18 at 21:42
  • Sounds complicated. I suppose it depends on how big this application is going to be. How many developers will be working on it? – Robert Harvey May 29 '18 at 21:45
  • It was a broad question, but I'm interested in making an API for fun by myself. – JacopoStanchi May 29 '18 at 21:49
2

I think it is usually a good idea to decouple the website from the database, thus a general API to the database would be desirable and in some instances more secure. To really benefit you ideally would also add some sort of API Gateway that hides the complexity, additionally as you mentioned you might then need some additional sort of authorization like JWT tokens (for instance).

Now in reality, while this all sounds nice, is scalable and would allow for a multitude of clients beyond browsers without too much additional burden, it might just be overkill. It always depends on your use case, but in a scenario as you described where a single instance handles both the web servers and the API endpoint, it likely won't be too beneficial to even create an API. If there is a good reason for an API you might be better off doing things right to begin with and separate the database service from the webserver in the first place.

Just my two cents...

| improve this answer | |
1

Dogfooding is a beneficial practice. If you are providing your API to others, you should probably use it yourself.

If, however, your website uses the API in a substantially different way, or does things that shouldn't be exposed via the API, it might be better to go directly to the database.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.