# How to Access Raw POST Data in Rails

*Published on 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_&nbsp;[_clientwork_](/freelancing)_, 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.

```ruby
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&nbsp;[`raw_post`](https://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-raw_post)&nbsp;method in Rails which does this for you. Here's what the method is doing behind the scenes.

```ruby
# 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:

```ruby
request.raw_post
```

I am surprised I never ran into this method before, as it has existed in Rails for over two decades, and&nbsp;[was introduced by none other than Tobias Lütke](https://github.com/rails/rails/commit/2f11b7cfeeb9a25225c2f31e95afabcd3e43bb41), the founder of Shopify! Quite a piece of open source history, isn't it?

