scalahttphttp-headersscala-dispatch

Methods to insert Oauth headers in Scala Dispatch 0.9.5?


Using the rather simple and elegant Scala Dispatch HTTP library. Since the Twitter Search API is now using OAuth 1.0A, I obviously need to start injecting Consumer and AccessToken information. I've got a simple request below:

val request = url("https://api.twitter.com/1.1/search/tweets.json?q=%23%sresult_type=mixed&count=4" format w.queryValue)
val response = Http(request OK as.String)

What's a way to add headers to this if I already know my Consumer and AccessToken information? The documentation is rather scarce. Thanks!


Solution

  • I'm not familiar with the OAuth API, but Dispatch allows you to add arbitrary HTTP Request headers with the <:< method/operator.

    So mashing together your code example above and this "Authorizing a request" example from Twitter's Developer site, you might get something like this:

    val authentication = """OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",  oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318622958", oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0""""
    
    val request = url("https://api.twitter.com/1.1/search/tweets.json?q=%23%sresult_type=mixed&count=4" format w.queryValue)
    val authHeader = Map("Authentication" -> authentication) 
    val requestWithAuthentication = request <:< authHeader
    val response = Http(requestWithAuthentication OK as.String)
    

    I haven't verified whether this actually works, but hopefully it should get you going in the right direction.