0

I dont know how to put my key into my requests so they are sent back as

{"status"=>"400", "message"=>"Token parameter is required."}

This is the code I have been using

require 'net/http'
require 'json'

token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
uri = URI(url)
response = Net::HTTP.get(uri)
response.authorization = token
puts JSON.parse(response)

I have tried a couple different things I've found on the internet but all of them just give errors for

undefined method `methodname' for #<String:0x00007fd97519abd0>
Gerold Astor
  • 189
  • 9

1 Answers1

4

According to the API documentation (based on the URL you referenced), you need to provide the token in a header named token.

So, you should probably try some variation of the below (code untested):

token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
uri = URI(url)
request = Net::HTTP::Get.new(uri)
request['token'] = token
response = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(request)
end

More information about Net:HTTP headers can be found in this StackOverflow answer.


As a side note, if you are not locked on using Net::HTTP, consider switching to a friendlier HTTP client, perhaps HTTParty. Then, the complete code looks like this:

require 'httparty'

token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
response = HTTParty.get url, headers: { token: token }

puts response.body
DannyB
  • 12,810
  • 5
  • 55
  • 65