How to validate header parameters with Sinatra?

旧时模样 提交于 2020-01-25 19:29:41

问题


I'm working on a simple API with Sinatra and I have a route like this one:

get '/api/v1/invoice/:biller', :provides => [:json] do
   respond_with invoice( request )
end

It works like a charm when I don't send any header params, but when I send:

  • Accept
  • Content-Type

Then I got a 404 Not Found error and the classic Sinatra error 'Sinatra doesn't know this ditty'.

How can I validate specific header params on Sinatra?

Edit

This is the actual header (Accept) with a curl example:

curl -H "Accept: application/vnd.tpago.billpayment+json" -X GET "http://localhost:3540/api/v1/invoice/5947647"

Thanks!


回答1:


If you change your request to:

curl -H "Accept: application/json" -X GET "http://localhost:3540/api/v1/invoice/5947647"

It will work as Neil suggest or if you modify your Sinatra app to:

configure do
  # include new mime type
  mime_type :tpago, 'application/vnd.tpago.billpayment'
end

# add into provide options
get '/api/v1/invoice/:biller', :provides => [:tpago,:json] do
   respond_with invoice( request )
end

Now, the following request will work:

curl -H "Accept: application/vnd.tpago.billpayment" -X GET "http://localhost:3540/api/v1/invoice/5947647"

I am not totally sure, but I think "+" sign doesn't work on Accept header. I didn't find any reference about it on w3 documentation.




回答2:


Thanks tlewin!

I applied your solution but then I discovered an issue with 'respond_with'. It was always returning a 408 Not Acceptable so I went to the Sinatra's documentation, so I used a respond_to:

get '/api/v1/invoice/:biller', :provides => [:tpago,:json] do
  result = invoice( request )
  respond_to do |f|
    f.on('application/vnd.tpago.billpayment+json') { result.to_json }
  end
end

And now it's working! :D

Thank you again!



来源:https://stackoverflow.com/questions/20003755/how-to-validate-header-parameters-with-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!