Faraday: Middleware for Making Fetch Requests

Faraday the Pains Away

Michael Faraday was one of the most important scientists in history. His discoveries in electromagnetism and electrochemistry changed the world and continue to influence our daily lives to this day. While it doesn’t share anything besides his name, the Faraday gem will similarly make your life easier. With Faraday, fetch requests from a controller in your Ruby on Rails project becomes a breeze.

According to the official docs:

“Faraday is a simple, flexible HTTP client library, with support for multiple backends. Faraday also is a middleware.”

the key is that Faraday is simple. Compared to other concepts, Faraday is a breeze to setup and get going. To use it simply open your Gemfile and include:

gem 'faraday'

and run a trusty

bundle install

Let’s get a controller spun up and try it out.

Faraday supports several HTTP verbs. Let’s try a simple GET request. In our newly created controller we can create a response variable and let Faraday do its magic

TestController.rb

response = Faraday.get 'http://example.com/somewhere/movies'

this will return a faraday response object with a response status, header, and body. You can access the information by calling:

response.status
response.header
respones.body

If you need to specify query parameters or request headers when making a request it as also incredibly easy:

url = ‘http://example.com/somewhere/movies'
resp = Faraday.get(url, {a: 1}, {'Accept'=> 'application/json'})

This should send a GET request to our 1)url, 2) to the movie with the desired id, 3) with the desired header.

When it comes to making a request with a body, like a POST request, we use a different but equally simple syntax.

# POST 'application/x-www-form-urlencoded' content
url = ‘http://example.com/somewhere/movies'
resp = Faraday.post(url, collection: Aliens)
# POST JSON content
resp = Faraday.post(url, '{"collection": "Aliens"}',
"Content-Type" => "application/json")

The coolest thing going on here is Faraday’s ability to convert hashes to values that can be sent to the desired URL easily!

All of this is basic but that is the beauty of Faraday. It takes a fairly verbose process and streamlines it down to a DRY experience. Using Faraday in concert with the Figaro gem, you can hide the keys to your API fetches with ease as shown in my last blog post. Happy Coding!

I love traveling, music, and movies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store