I recently helped debug Grape#1880, an issue a developer had with HTTP headers in Grape and Rack. It wasn’t immediately obvious.
Test API
Let’s write a simple Grape API that returns a value for a header.
Default Headers
The default headers in a Rack test are Cookie
and Host
.
Curl sends more headers by default.
Pascal Case Conversion
Headers in Grape are always converted to pascal-case.
This means that a pascal-case-looking header ReticulatedSpline
is converted to Reticulatedspline
.
And a lowercase reticulated-spline
is converted to Reticulated-Spline
, similarly to User-Agent
.
Rack
Rack stores HTTP headers in ENV
as all uppercase with an HTTP_
prefix. You can pass the Rack env as the the second parameter in your specs. In the example below HTTP_RETICULATED_SPLINE
becomes Reticulated-Spline
and SOMETHING_ELSE
is only available in ENV['SOMETHING_ELSE']
and is not a header.
To avoid confusion use the header
helper that behaves as one would expect.
Rails
Rails get
takes a Hash
, but it’s still a wrapper on top of Rack, sort of. You can specify a header as Header
or HTTP_...
.
Links
- grape#headers: Header handling documentation in Grape.
- grape#1880: Issue with case insensitive headers.
- grape-on-rack#18: Demonstrate header handling in Rack.
- grape-on-rails#9: Demonstrate header handling in Rails.