DanielNordby
DanielNordby

Reputation: 579

API calls in Rails

This feels like a dumb question, but the more I think about it the more confused I get: how (and where? Model? Controller?) do I make an API call in a Rails app?

I need to make a string of API calls, capture the returned data, save pieces of that data to a database, and then use that database info to make another API call. That repeats a couple times, building the data I need for the final API request (which winds up being a POST request, but I would probably need to save the "success" or "fail" message to the database too).

Typically, I use AJAX in my non-rails projects to APIs to get what I need...but those are more display-only situations, so I've never needed to save what the API returned. I think about 90% of my confusion stems from the fact that I'm trying to figure out how to make an AJAX call in a rails model, when really I should (somehow, and here is where my knowledge ends) be making an HTTP request in my model.

I may be missing something fundamentally about Ruby and/or Rails that allows me to make HTTP requests, so I would highly value any feedback/guidance on how to get started making these necessary API calls!

Upvotes: 0

Views: 1619

Answers (1)

OneSneakyMofo
OneSneakyMofo

Reputation: 1289

There are plenty of libraries/gems that do this:

Of those, I would say Rest Client is easiest.

Also, I usually create a service class to do this instead of a model or a controller to contain the code in its own place for ease of use.

Upvotes: 1

Related Questions