为了从我发出请求的API获取JSON,我需要在我的请求中添加.json
扩展名。例如:
/test/api/people/2323 # returns XML
/test/api/people/2323.json # returns JSON
请求的应用程序使用Rails与她的宝石。根据{{3}},您可以指定这样的集合路径。
collection_path "organizations/:organization_id/users"
似乎没有办法添加具有该格式的扩展程序。它不适用于:
collection_path "test/api/people/:id.json"
或
collection_path "test/api/people.json"
以下是Her
的初始化程序:
LOCAL = Her::API.new
LOCAL.setup url: "https://example.com", headers: { "Content-Type" => "application/json" } do |config|
config.use Faraday::Request::UrlEncoded
config.use Her::Middleware::DefaultParseJSON
config.use Faraday::Adapter::NetHttp
end
Her / Faraday的设置是否缺少一个步骤,还是有一些方法可以在不指定扩展名的情况下请求JSON?我想访问的API也是用Rails编写的。
答案 0 :(得分:3)
有没有办法在不指定扩展名的情况下发出JSON请求?
是的,您需要添加中间件Her::Middleware::AcceptJSON
。它所做的只是添加"Accept: application/json"
HTTP标头。
非常简单:),这里是the docs和source code,只有17行代码。
现在您的文件config/initializers/her.rb
看起来像这样:
Her::API.setup url: "https://example.com" do |config|
config.use Faraday::Request::UrlEncoded
config.use Her::Middleware::DefaultParseJSON
config.use Faraday::Adapter::NetHttp
# middleware to make a json request by default
config.use Her::Middleware::AcceptJSON
end