Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External API calls from the frontend or backend?

Scenario: I have a Node and Angular web app. It needs to call an external api (a third party service) for data (more specifically this: https://api.represent.me/api/questions/).

Question: Is it better to make this external call from the Angular frontend: GET http://thirdpartyservice.com/api/data or have the frontend calling a same domain Node endpoint: GET http://example.com/node-backend-api which then calls GET http://thirdpartyservice.com/api/data which then fetches and processes the data from the third party api before passing it back to angular?

Thoughts:

  • I guess two api calls is less desirable, but it is on the same domain so would this not really be an issue?
  • GETing from the Node side would be more secure (especially if secret keys were used), and also mask the fact that a third party service is used.
  • CORS stuff might get in the way if calling from the frontend.
  • Is context key here, e.g. calling font apis from the frontend is probably best, but fetching and needing to process data is probably better from the backend.

What do others recommend (and do) and are there any other for or against points to add to the 'thoughts' too?

like image 350
timhc22 Avatar asked Sep 26 '16 14:09

timhc22


2 Answers

It depends on what your 3rd party API requires.

If you need some credentials to call the API it's probably better to handle the call in backend because of security concerns.

If the API delivers time sensitive data, like some auto-complete information as you type, it might be good to not do the extra roundtrip to the backend and call it from the frontend.

You might create a subdomain which points to the 3rd party server, like 3rdparty-api.yourdomain.com, this removes a lot of cross-domain issues. But this needs cooperation of your 3rd party provider.

So, there is no clear yes or no answer but it depends on the situation and focus of your API.

like image 109
Wolffc Avatar answered Oct 27 '22 14:10

Wolffc


Your solution looks fine, the only thing that may get in your way is if the 3rd party API you are using provides any sort of analytics. If you call it from Node you will overwrite the Agent and IP information that would be gathered if you called from UI. Other than that, I believe making the request directly from UI could reduce a little bit the load on the server, but I don't know if that matters to you.

like image 39
natanael Avatar answered Oct 27 '22 15:10

natanael