# Working with HTTP Requests in Rails

*Published on March 07, 2025*

Tags: Controllers

---


_This is the third post in my deep-dive series on Rails Controllers. Check out the first two posts here:_ [_Introduction to Rails Controllers_](/new-series-on-rails-controllers) _and_ [_Understanding Rails Parameters_](/rails-parameters)_._

HTTP is a request-response based protocol. The browser (acting as the client) sends an HTTP request to the server (your Rails application). The server then parses the request, processes it, and generates an HTTP response, which is sent back to the browser. Each request carries a bunch of useful information that your application frequently relies on to handle the request properly.

Rails offers a simple and straightforward interface to work with the current HTTP request hitting your application. It also exposes a bunch of super useful methods to access details like request data, including input parameters, URLs, paths, and the request body that comes with each request.

In this post, we’ll explore some of the most commonly used methods for inspecting incoming HTTP requests. First, let’s take a look at how you can access the request object inside a controller class.

## **Accessing the Request**

To obtain an instance of the current HTTP request in your controller class, use the&nbsp;`request`&nbsp;method, which returns an instance of the&nbsp;`ActionDispatch::Request`&nbsp;class.

```ruby
class RequestsController < ApplicationController
  def show
    puts request  # #<ActionDispatch::Request:0x0000000128d38c08>
  end
end
```

Now you might be wondering where this&nbsp;`request`&nbsp;method (is it even a method?) is defined in the Rails controller hierarchy. So let's inspect the Rails codebase, specifically the&nbsp;`ActionController::Metal`&nbsp;class, which is the great-granddaddy of your application controllers.

```ruby
module ActionController
  class Metal
    # The ActionDispatch::Request instance for the current request.
    attr_internal :request
  end
end
```

The&nbsp;[`attr_internal`](https://api.rubyonrails.org/classes/Module.html#method-i-attr_internal_accessor)&nbsp;method is provided by Rails, not part of standard Ruby. It declares an attribute reader and writer backed by an internally-named instance variable,&nbsp;`@_request`. This is particularly useful when you want to avoid naming&nbsp;conflicts with public methods or when you want&nbsp;to clearly distinguish internal state variables.

It’s worth noting that the&nbsp;`request`&nbsp;object is only accessible within controllers — this is intentional as a controller is the correct level of abstraction to handle incoming requests.  
  
Just wanted to make that clear, as I often see questions like, “How can I access the request object in my models or service objects?” The short answer is:&nbsp;**you don’t.**&nbsp;Instead, extract only the necessary data from the request in the controller and pass that data to your models or service objects, instead of trying to access to whole request in there.

The&nbsp;`ActionDispatch::Request`&nbsp;instance provides a bunch of methods to examine the incoming HTTP request. Let's take a look at some of the important and commonly used methods below.

## **Retrieving the Request Path**

The&nbsp;`path`&nbsp;method returns the request's path information. If the user visits your application at&nbsp;**https://basecamp.com/projects/rails**, the&nbsp;`path`&nbsp;method will return&nbsp;`projects/rails`.

```ruby
class ProjectsController < ApplicationController
  def rails
    url_path = request.path # /projects/rails
  end
end
```

Now, if you're like me and your first instinct is to take a look at the Rails API docs every time you come across a new method, you'd be surprised to find that the list of methods listed under the&nbsp;[`ActionDispatch::Request`](https://api.rubyonrails.org/classes/ActionDispatch/Request.html)&nbsp;class doesn't have a&nbsp;`path`&nbsp;method. So where's that coming from?

As always, let's open the Rails codebase and take a peek at the&nbsp;[source code for the&nbsp;`ActionDispatch::Request`&nbsp;class](https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/http/request.rb#L21). Here's the important part:

```ruby
module ActionDispatch
  class Request
    include Rack::Request::Helpers
  end
end
```

Let's follow the trail and open the&nbsp;`Rack::Request::Helpers`&nbsp;module located in the Rack gem (run the&nbsp;`bundle open rack`&nbsp;command).&nbsp;[Here's](https://github.com/rack/rack/blob/main/lib/rack/request.rb#L154)&nbsp;the source code.

```ruby
module Rack
  class Request
    module Helpers
      def path
        script_name + path_info
      end
    end
  end
end
```

So that's where the&nbsp;`path`&nbsp;method is coming from. The&nbsp;`ActionDispatch::Request`&nbsp;class&nbsp;[includes](https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/http/request.rb#L21)&nbsp;the&nbsp;`Rack::Request::Helpers`&nbsp;module, which provides the&nbsp;`path`&nbsp;method.

However, the&nbsp;`path`&nbsp;method only returns the URL&nbsp;`path`&nbsp;component, and doesn't include any query parameters. If you want the full path, including any query params if present, you'll have to use the&nbsp;`fullpath`&nbsp;method on the request.

```ruby
# URL: https://example.com/projects/rails?page=22

class ProjectsController < ApplicationController
  def rails
    path = request.path           # /projects/rails
    fullpath = request.fullpath   # /projects/rails?page=22
  end
end
```

In practice though, if you need to work with the query params, you'd typically use the&nbsp;`params`&nbsp;object instead of reading them from the URL. For example, given the same URL endpoint above, you'd access the&nbsp;`page`&nbsp;query param as follows:

```ruby
puts params[:page]  # 22
```

To learn more about Rails parameters, check out my previous post in the series on Rails controllers:

[Understanding Rails Parameters](/rails-parameters)

### **Retrieving the Request URL**

To access the complete URL including the domain for the incoming request, you can use the&nbsp;`url`&nbsp;method.

```ruby
class ProjectsController < ApplicationController
  def rails
    url = request.url     # http://www.example.com/projects/rails?page=22
    path = request.path   # /projects/rails
  end
end
```

### **Retrieving the Request Host**

If you just want the domain name, you can retrieve the host of the incoming request via the&nbsp;`host`&nbsp;method.

```ruby
puts request.host # www.example.com
```

### **Retrieving the Request Method**

The&nbsp;`method`&nbsp;method returns the HTTP verb for the request.

```ruby
request.method  # "GET"
```

The nice thing about this method is that it will return the original value of the request method, even if it was overridden by any middleware.

## Working with Headers

The&nbsp;`headers`&nbsp;method on&nbsp;`ActionDispatch::Request`&nbsp;provides access to the request's HTTP headers.

```ruby
request.headers["Content-Type"] # "text/plain"
```

Here's the implementation of this method:

```ruby
# actionpack/lib/action_dispatch/http/request.rb

def headers
  @headers ||= Http::Headers.new(self)
end
```

The&nbsp;`Http::Headers`&nbsp;provides a hash-like storage, giving you all the headers associated with this request. You can get and set a value of a particular header just like you get and set values for a hash.

**Important:**&nbsp;If you just call the&nbsp;`headers`&nbsp;method in a controller, it will give you the response headers, i.e. headers sent with the response.

```ruby
class ProjectsController < ApplicationController
  def rails
    headers == response.headers  # true
  end
end
```

To access the request's headers, remember to use&nbsp;`request.headers`&nbsp;as follows:

```ruby
class ProjectsController < ApplicationController
  def rails
    http_method = request.headers["REQUEST_METHOD"]
  end
end
```

There is one gotcha when accessing headers like this. If a particular header doesn't exist, Rails will return&nbsp;`nil`, which may not what you want. Sometimes, you want to know if the header is indeed not present, and use a default value if it's missing. For this, use the&nbsp;`fetch`&nbsp;method on the&nbsp;`Headers`&nbsp;class.

It accomplishes two things: When the header is not present, it will raise a&nbsp;`KeyError`. Alternatively, you can pass an optional second argument that will be returned if the headers is not present on the request.

```ruby
class ProjectsController < ApplicationController
  def rails
    request.headers.fetch("X_REQUEST_METHOD")  # KeyError: X_REQUEST_METHOD
    request.headers.fetch("X_REQUEST_METHOD", "GET")  # "GET"
  end
end
```

Finally, you can use the&nbsp;`key?`&nbsp;or&nbsp;`include?`&nbsp;methods to check if a particular header value is present or not, just like a regular Hash.

## Request IP Address

💡 In general, treat IP addresses as untrusted, user-controlled input and use them for information-purposes only.

You can use the&nbsp;`ip`&nbsp;method to retrieve the IP address of the user (or client) that make the HTTP request to your Rails application.

```ruby
ip_address = request.ip  # "127.0.0.1"
```

In addition, Rails also provides a&nbsp;`remote_ip`&nbsp;method on the request object. In development (or often in production), you will see the same value for both.

```ruby
remote_ip_address = request.remote_ip  # "127.0.0.1"
```

**So, what's the difference between the**&nbsp;**`ip`**&nbsp;**and**&nbsp;**`remote_ip`**&nbsp;**methods?**

Sometimes, the client doesn't directly send the request to you, but via intermediate proxies, each of which forwards it to the next proxy before the request reaches your application. In these cases, the server would only see the final proxy's IP address, which is not that useful, as it's often a load balancer.

To solve this, each proxy is supposed to set the&nbsp;[`X-Forwarded-For`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)&nbsp;header. This header identifies the originating IP address of a client connecting to a server via a proxy server.

```text
X-Forwarded-For: <client>, <proxy>, …, <proxyN>
```

When a request goes through multiple proxies, the IP addresses of each successive proxy are listed. The rightmost IP address is the IP address of the most recent proxy and the leftmost IP address is the address of the originating client.

Rails provides a&nbsp;`RemoteIp`&nbsp;middleware which calculates the IP address of the remote client making the request, and exposes it via&nbsp;`remote_ip`&nbsp;method on the request.

Don't use this middleware if you're not using at least one proxy, otherwise it exposes you to IP spoofing attack (since any client can claim to have any IP address by setting the above HTTP header).

## Accessing Request Body

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 incoming request body.

```ruby
def request_body
  @request_body ||= (
    request.body.rewind
    request.body.read
  )
end
```

However, Rails provides an awesome&nbsp;`raw_post`&nbsp;method which does it for you. In your Rails controller, you can access this method as follows:

```ruby
request.raw_post
```

💡 Here's an interesting fact: The&nbsp;`raw_post`&nbsp;method was introduced by&nbsp;[Toby Lütke](https://github.com/rails/rails/commit/2f11b7cfeeb9a25225c2f31e95afabcd3e43bb41), the founder of Shopify.

## Unique Request ID

In Rails, each request gets its own unique identifier, useful for end-to-end tracing of a request, logging, and even for debugging. This is set by the&nbsp;`ActionDispatch::RequestId`&nbsp;middleware and you can access it using the&nbsp;`request_id`&nbsp;method on the request.

```ruby
class ProjectsController < ApplicationController
  def rails
    id = request.request_id  # "1659c4b4-1557-43dc-8883-f03968888f32"
  end
end
```

You can also use&nbsp;`request.uuid`&nbsp;which is an alias of the above method.

## Summary

Here's a quick glance at most of the methods available on the request object.

```ruby
require "test_helper"

class ProjectsControllerTest < ActionDispatch::IntegrationTest
  test "methods on the request object" do
    post projects_publish_path(tag: "programming"), params: { title: "Ruby on Rails", description: "A web framework for Ruby" }, headers: { "X-Project-Id" => "58432" }

    assert_equal "title=Ruby+on+Rails&description=A+web+framework+for+Ruby", request.raw_post
    assert_equal 56, request.content_length
    assert_equal "/projects/publish", request.path
    assert_equal "/projects/publish?tag=programming", request.fullpath
    assert_equal "58432", request.headers["X-Project-Id"]
    assert_equal "127.0.0.1", request.ip
    assert request.local?
    assert_equal "application/x-www-form-urlencoded", request.media_type
    assert_equal "POST", request.method
    assert_equal :post, request.method_symbol
    assert_equal {"tag"=>"programming"}, request.query_parameters
    assert request.request_id
    assert_equal {"title"=>"Ruby on Rails", "description"=>"A web framework for Ruby", "tag"=>"programming", "controller"=>"projects", "action"=>"publish"}, request.parameters
  end
end
```

Hope that helps.

Update (2025): [You Can Now Access Bearer Tokens Directly from Request](/rails-access-bearer-token-from-request)

