当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - Passing in API Key and Parameters with RestClient

问题描述:

In my application I have a user pass in a form that fires out an API request and then displays the results of the query.

I allow the user to to select many or few parameters. The problem I get is a 401 Authorization error and I believe that is because the apikey isn't being recognized (there is no password, username needed for the api and no limits).

Application:

post '/search' do

phrase = params.fetch "phrase" #mandatory

@delimiters = ""

start_date = params.fetch "start_date"

start_date.empty? ? start_date = "" : @delimiters << "From #{start_date},"

end_date = params.fetch "end_date"

end_date.empty? ? end_date = "" : @delimiters << "To #{end_date}"

api_result = RestClient::Request.execute(method: :get, url: "capitolwords.org/api/1/text.json?phrase=#{phrase}

&page=0&apikey=",

headers: {params: {:start_date => start_date,

:end_date => end_date},

:Authorization => ENV['SUNLIGHT_API_KEY']},

timeout: 10)

end

The delimiter is what I'm using to catch all the parameters passed in so I can show the user what they searched by. I've read the documentation at https://github.com/rest-client/rest-client and they don't mention passing in api keys.

This is part of a refactoring process - passing in the parameters one by one as #{@parameter_example} works but makes my code less readable and I then manually must set up @parameter_example = "&parameter_example=#{parameter_example}" which seems overly verbose.

网友答案:

Judging from the capitalwords.org documentation, it seems that the api key along with the phrase, start_date, end_date params should be passed as part of the query string. So your rest-client request should look like this:

api_result = RestClient::Request.execute(method: :get, 
                                            url: "capitolwords.org/api/1/text.json", 
                                        headers: {params: {:phrase => phrase, 
                                                           :start_date => start_date,
                                                           :end_date => end_date,
                                                           :page => 0,
                                                           :apikey => ENV['SUNLIGHT_API_KEY']}}, 
                                        timeout: 10)       

I think that in order to pass params like this (using headers params hash) to RestClient::Requeest.execute then the url you request should not include any params or else rest-client fails to produce the correct url. That's why I moved page and phrase from url into params phrase hash.

网友答案:

Did you remember to do the following at the top of the file?

require 'dotenv'
Dotenv.load
分享给朋友:
您可能感兴趣的文章:
随机阅读: