HTTParty + JSON-LD内容类型响应

时间:2020-06-15 22:19:48

标签: json ruby sinatra json-ld httparty

我们如何处理仅接受“ application / ld + json”的HTTP请求?我有一个简单的GET请求,仅接受application / ld + json Content-Type。示例代码:

app.rb :( Sinatra服务器接受来自客户端的请求,充当中间件)

helpers do
  def institutions(payload)
    ApiRequest.new(payload).institutions
  end
end

get '/' do
  payload = {}
  payload['fullSearch'] = params['fullSearch']
  payload['token'] = request.env['HTTP_X_ID_TOKEN']
  institutions(payload).body
end

api.rb

class ApiRequest
  include HTTParty
  base_uri 'https://api.dev.example.com'

  def initialize(params)
    @token = params['token']
    @options = {
      query: { fullSearch: params['fullSearch'] },
      headers: headers
    }
  end

  def headers
    { Authorization: "Bearer #{@token}", Accept: 'application/ld+json' }
  end

  def institutions
    self.class.get('/institutions', @options)
  end
end

所以我知道要添加一个before方法来获取相应的内容类型

before do
    content_type :json
end

对于ld + json内容类型,我该怎么做?在Ruby的范围内,JSON和JSON-LD之间有什么区别吗?还是只假设内容为JSON并正常解析?

1 个答案:

答案 0 :(得分:0)

您可能会看一下sinatra-linkeddata gem,它会返回JSON-LD,尽管通过序列化程序可以生成RDF图。否则,只需注册:jsonld Minne类型。

大多数JSON-LD处理器将很乐意处理纯JSON,但是有一些细微的差异。