Ask A Question

Notifications

You’re not receiving notifications from this thread.

Is it a good practice to call third party api before every controller action?

Ali Ahmed asked in Rails

Is it a good practice if we can call a REST api on before_action hook of application_controller.rb and store the response in helper method?

My Scenario is that I wanna call an API from another app and get its data for a specific user role after that user is signed in. I am using Warden gem and I also have its after_authentication hook to do that but how do I make sure to use that API response in my app (i.e helpers/views/controllers etc).

I am having a bad feeling to do it on every request, I need to know if there could be a pattern or any better approach that solves these kind of problems.

Reply

Hey Ali,

This is a great question. What I would probably do for this is I would create a model that would cache the results of the API call.

Then I would use a before_action in ApplicationController to load that model for the current user. If it didn't exist, you can have it hit the API and save the results in the model.

The first request, the model shouldn't exist, but every time afterwards it will so you won't have to hit the API every time.

I wouldn't use the after_authentication hook exclusively just because there may be situations that come up where that method doesn't succeed and a user might not have any results. Imagine that external service went down for an hour or they returned a 500 error for some reason. If you do it every request instead, you can always hit their API as needed without worrying about missing records ever.

Reply

Thanks Chris, expected answer with clarity. Appreciate it sir.

However, one minor gotcha that I am looking forward to come up, that how do I make sure that my model is always updated with new values from that API?

Let's say API now returns new results and my before_action hook only checks that if the model either exists or not with the value. How would I know if I have to hit the API again on each request and compare, maybe the timestamp attribute or, any others attributes that reflect that there now new results and then I now have to update the model.

Is there any easy logic in your experience?

Reply

Depends on how up-to-date you want it to be. If you're fine with every day, then write a cron job to sync and update every day or something.

If you need it to be more real-time, then trigger an API request after you load the record to sync it with the latest value. They may also provide webhooks to send you the changes as needed which you would save you from making API requests which would be nice.

Reply

Thanks Chris for clarity.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.