纽约公共图书馆搜索查询

时间:2013-05-25 00:33:03

标签: ruby json

我正试图通过他们的api访问纽约公共图书馆的数字馆藏。

我用来拨打电话的红宝石代码是:

require 'sinatra'
require 'pp'
require 'httparty'


    get '/' do
        url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
        uri = URI.parse(url)
        http = Net::HTTP.new(uri.host, uri.port)

        headers = { "Authorization" => "Token token=mytoken" }
        request = Net::HTTP::Get.new(uri.request_uri, headers)
        response = http.request(request)
        puts response
        @response = response.body
        erb :index
    end

所以,有几个问题:

  1. 这不会产生任何结果,终端中的puts响应不会返回任何内容,甚至不会出现错误消息。我究竟做错了什么?

  2. 在任何情况下,如何在uri字符串的末尾附加查询?通过添加?接下来是查询?所以,例如,?leonardodavinci

1 个答案:

答案 0 :(得分:1)

建议您在irb命令提示符处玩游戏,例如

irb [enter]

看起来好像没有被授权?我最终得到=> nil

irb(main):003:0> require 'sinatra'
=> true
irb(main):004:0> require 'pp'
=> true
irb(main):005:0> require 'httparty'
=> false
irb(main):006:0> url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
=> "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
irb(main):007:0>   uri = URI.parse(url)
=> #<URI::HTTP:0x9826744 URL:http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json>
irb(main):008:0>  http = Net::HTTP.new(uri.host, uri.port)
=> #<Net::HTTP api.repo.nypl.org:80 open=false>
irb(main):009:0> headers = { "Authorization" => "Token token=mytoken" }
=> {"Authorization"=>"Token token=mytoken"}
irb(main):010:0> request = Net::HTTP::Get.new(uri.request_uri, headers)
=> #<Net::HTTP::Get GET>
irb(main):011:0> response = http.request(request)
=> #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>
irb(main):012:0> puts response
#<Net::HTTPUnauthorized:0x9938a74>
=> nil
irb(main):013:0>