Search code examples
rubysinatrainstagraminstagram-api

Instagram access_token returning BadRequest error


I'm working with the Instagram gem and getting an unexpected bad request error when calling Instagram.user_recent_media.

get '/api/photos' do
    client = Instagram.client(:access_token => session[:access_token])
    puts 'access token: ' << session[:access_token].inspect
    id = params[:id]

    photos = Instagram.user_recent_media(id, {:max_id => params[:max_id]})
end

It's throwing this error:

Instagram::BadRequest - GET https://api.instagram.com/v1/users/35099128/media/recent.json?client_id=12345&max_id=: 400: you cannot view this resource:

In the line where I put the access_token, it is printing out an access token so it clearly exists. When I curl the request I get the same error,

{"meta":{"error_type":"APINotAllowedError","code":400,"error_message":"you cannot view this resource"}}

but when I paste the request into the Instagram API console I get the expected results (JSON of user photo data). This is a user who I follow. For a little while I was having my access_token seemingly expire immediately and throwing a specific 'access token not valid' error but that has gone away, so I'm not sure what else could be causing this error.


Solution

  • The access_token or client_id that you are using in your Ruby code must be different from the one you are using in your web browser when you test the Instagram API console. That is the only explanation.

    The ID that you are using in your question (35099128) is for a private Instagram account. The reason it works in the Instagram API console is because you are already following the private account with your Instagram account.

    EDIT

    To be 100% sure you have the correct access_token in your code you can try to make the query directly without the extraneous variables. Use the following format (taken from this question):

    https://api.instagram.com/v1/users/20282699/media/recent?access_token=510573486.ab7d4b6.d8b155be5d1a47c78f72616b4d942e8d

    Replace the user-id and access_token with the one your are printing in your code.

    https://api.instagram.com/v1/users/35099128/media/recent?access_token=ACCESS_TOKEN_HERE

    EDIT2

    Since the access_token is definitely valid, it is clear that your request formed in the Ruby code is missing the access_token. The problem is this line:

    photos = Instagram.user_recent_media(id, {:max_id => params[:max_id]})
    

    has no knowledge of your access_token, likely because you're are not using the client object that you previously defined. Try changing it to this (or the proper equivalent):

    photos = client.user_recent_media(id, {:max_id => params[:max_id]})