How to use basic authentication with httparty in a Rails app?

Dr.Bob picture Dr.Bob · Oct 2, 2011 · Viewed 37.9k times · Source

The command line version of 'httparty' with basic authentication works simple and great:

httparty -u username:password http://example.com/api/url

But now I'm looking for the way I can add the basic auth to a HTTParty.get call from within a Rails app. First of all, for testing purposes, I want to hard code the login credentials in the Controller. Just to make sure it works. But I can't find any documentation or examples how you can pass these along.

A HTTParty.get without credentials works fine:

@blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json")

But I don't see how I can make a variation on this that accepts the -u username:password part.

The next challenge for me (am very new to Ruby/Rails) is to get the user credentials from a user form and pass it along dynamically, but most important for me now it to get the hard coded version to work.

Answer

Vasiliy Ermolovich picture Vasiliy Ermolovich · Oct 2, 2011
auth = {:username => "test", :password => "test"}
@blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json", 
                     :basic_auth => auth)