June 26, 2024
How to Access Raw POST Data in Rails
I haven't published any new posts in the past few weeks because we recently welcomed a baby girl into the family ๐, and combined with all the ongoing clientwork, it has become quite challenging to find quality time for writing. I really appreciate your patience though, and be assured that once things settle down, I will return to a regular posting schedule โ๏ธ
If you are building an API or any sort of web services, you often want to work with the raw, unchanged request body. For a long time, I used to add this helper method in my Rails controllers to access the the incoming request body.
def request_body
@request_body ||= (
request.body.rewind
request.body.read
)
end
Recently, in one of the code reviews at work, I came across the raw_post method in Rails which does this for you. Here's what the method is doing behind the scenes.
# actionpack/lib/action_dispatch/http/request.rb
def raw_post
unless has_header? "RAW_POST_DATA"
set_header("RAW_POST_DATA", read_body_stream)
body_stream.rewind if body_stream.respond_to?(:rewind)
end
get_header "RAW_POST_DATA"
end
def read_body_stream
body_stream.rewind if body_stream.respond_to?(:rewind)
return body_stream.read if headers.key?("Transfer-Encoding") # Read body stream until EOF if "Transfer-Encoding" is present
body_stream.read(content_length)
end
In your Rails controller, you can access this method as follows:
request.raw_post
I am surprised I never ran into this method before, as it has existed in Rails for over two decades, and was introduced by none other than Tobias Lรผtke, the founder of Shopify! Quite a piece of open source history, isn't it?
Subscribe to get future posts via email (or grab the RSS feed)
Comments (6)
Congratulations Akshay. Enjoy this beautiful time in your life.
Thank you, Deepak!
Congrats on the baby girl, Akshay!
Thank you Stephen!
First of all, ัongrats on your baby girl, Akshay! ๐๐ฃ Thanks for the post! ๐๐ป It's interesting to see an example of real problem where the method can be useful. ๐ค Just realized that I have never thought during my career about the need to get raw post data! ๐
Thanks Harry, appreciate the kind words ๐