David
David

Reputation: 4465

is there a way to modify or send custom headers on grape?

I'm using Goliath and Grape. On my goliath server it calls the grape api like so:

when '/posts' then FrameworksAPI::API.call(env)

On my grape api class, my method is as simple as this:

get '/:id' do
 Post.find(params[:id])
end

I'd like to modify the headers - specifically the 'Content-Length' but unsure how to.

Also i'd like to ask an additional question. How do i create callback/filters specifically before the method GET returns the result i'd like to modify the result.

Upvotes: 2

Views: 4061

Answers (2)

dj2
dj2

Reputation: 9618

The return from your FrameworksAPI::API.call(env) method will be a triplet [status_code, headers, body]. So, instead of just returning that from your case you'd do something like:

when '/posts' then
  status, headers, body = FrameworksAPI::API.call(env)
  headers['whatever'] = blah
  [status, headers, body]

You can also change the body, just be careful as the body maybe an array.

There is also a Content-Length middleware that is provided by Goliath. Content-Length is loaded by default although if you set a custom Content-Length it will take precedence. Just be carefull that other middlewares like the formattings don't change the body after you set your content-length.

Upvotes: 0

dB.
dB.

Reputation: 4770

Grape has a header helper for a few versions now.

header 'Content-Length`, 42.to_s

For your second question on modifying the body, try using after do ... at API level.

Upvotes: 7

Related Questions