Faraday POST request to getpocket API

tanookiben picture tanookiben · May 9, 2014 · Viewed 7.3k times · Source

I'm trying to set up OAuth for users of my Rails app to GetPocket (http://getpocket.com).

On Step 2 of the Pocket Authentication docs (http://getpocket.com/developer/docs/authentication), I'm having trouble constructing the exact Faraday request.

The following request works:

Faraday.post('https://getpocket.com/v3/oauth/request', {consumer_key: 'key', redirect_uri: 'localhost:3000'})

But I'd like the response to be in JSON. I'd like to be able to add a "Content-Type":"application/json" header to the request, but all my attempts don't seem to work.

Interestingly, when I do the following, the request fails (it returns a 200 but doesn't return a request token, just a whole HTML page):

conn = Faraday.new('https://getpocket.com/v3/oauth/request')
conn.post('/', {consumer_key: 'key', redirect_uri: 'localhost:3000'})

How do I get my Faraday POST request to the Pocket API to return results in JSON?

Answer

Jason Ng PT picture Jason Ng PT · Jun 10, 2014

For the 1-liner, I tried the below, which returns in JSON. The key header is X-Accept for the response format instead of Content-Type.

Faraday.post 'https://getpocket.com/v3/oauth/request', { 'consumer_key' => 'key', 'redirect_uri' => 'localhost:3000'}, { 'X-Accept' => 'application/json' }

The response is in JSON when I tried in IRB.

For the 2nd code section, I believe when you do a POST at '/', it only does a POST at the root domain, which is getpocket.com, thus returning the HTTP 200 and whole HTML page of the getpocket.com login page. From the output, there is a portion which indicates this (see below)

...snip... :url=>#<URI::HTTPS:0x000000028ab900 URL:https://getpocket.com/>, :request_headers=>{"User-Agent"=>"Faraday v0.8.9", "Content-Type"=>"application/x-www-form-urlencoded"}, ...snip..

Anyway, you can try the below which works for me when tested in IRB.

conn = Faraday.new('https://getpocket.com') conn.post('/v3/oauth/request', {consumer_key: 'key', redirect_uri: 'localhost:3000'}, { 'X-Accept' => 'application/json' })

hope this helps.