Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where best to fetch data from a third-party API service within the architecture of a Phoenix app

I have a question about how best to handle fetching data from a third-party API within the architecture of my phoenix app. Essentially, I have a controller that receives the client’s IP address as a parameter. I then need to fetch the geolocation associated with that IP address from an external API and store both in the database (i.e., ip and geolocation).

Right now my approach is to use a plug, and then return the result in the connection struct.

But I could also fetch the data by creating a function directly in the model, and then call it during the changeset operations.

Or perhaps there’s another alternative such as making it an OTP app.

Looking for some guidance on the best approach here, or at least the tradeoffs of one vs the other.

Although my scenario is specific, this is probably a common design question that people encounter.

like image 965
keruilin Avatar asked Jul 24 '17 22:07

keruilin


1 Answers

I can tell you how I'm approaching a somewhat similar problem. My application is a web app for sending SMS texts (I use Twilio as my API).

When a user submits their message (to_phone_number, body_text, etc.) I save it to the database without doing any additional work. I give it a separate status of "Queued."

Then, I have a GenServer in a loop picking up all Message where status == queued and doing the API calls. In the transaction, it changes the status to "Delivered", and that becomes visible to the user in the UI.

This won't be as useful an approach if your users are expecting geolocation data to show on-screen with their response. Anyway, this was the approach I took for my use-case...

like image 52
Lanny Bose Avatar answered Oct 16 '22 04:10

Lanny Bose