How to Access Raw POST Data in Rails
June 26, 2024
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
)
endRecently, 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)
endIn your Rails controller, you can access this method as follows:
request.raw_postI 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?