Faraday gem making requests from Rails Controller a cinch

Brett Cole
2 min readMay 21, 2018

--

For a previous small project I was doing I needed to figure out a way to make GET requests from my rails controller. I wasn’t quite sure how to go about it. After some searching I found Net::HTTP. After looking into it I felt it was just to complicated at the time.

Then someone suggested I look into the Faraday gem. Let me just say first gems are great. You can usually always find one to accomplish what you need. I have an internal debate on whether or not gems make us better or lazy programmers. But until I figure that out they are great to have. Ok back to Faraday.

Faraday describes itself as —

Faraday is an HTTP client lib that provides a common interface over many adapters (such as Net::HTTP) and embraces the concept of Rack middleware when processing the request/response cycle.

To get started we have to include gem 'faraday' inside our Gemfile and then run bundle. Then inside my controllers I created one called SearchesController. That file looked a little something like this.

Search Controller using Faraday gem

So if you couldn’t tell I’m trying to make a request to the Homeaway api to receive vacation listings. Inside the controller I’m making two requests, a POST request and a GET request. First a POST request to the homeaway api, but inside that method I’m also assigning my id and password which is Base64 encoded to the encode variable. Then I’m including variable inside the headers for my POST request. Finally assigning our response to @token_hash variable and calling our other method called homeaway_search. Now inside homeaway_search I’m making a GET request to search for vacation listings. But now inside our headers including the access_token returned from our POST. Finally assigning our search response to @search_result variable.

Faraday took me a little getting use to. But after working with it I think it works great and is easier then using things like Net::HTTP or any of the other adapters Faraday supports. The documentation for Faraday is great. This is just a quick example of using Faraday which I think is great.

Well that’s it for this blog post. I’m out for now until next time.

--

--

Brett Cole
Brett Cole

Written by Brett Cole

Full Stack Developer. Husband. Father.

No responses yet