Search code examples
curlruby-on-rails-5rails-apihttpie

How to have curl or httpie access subdomains locally with Rails 5


I'm building an API with Rails 5 and trying to test post requests locally on the command line with either curl or httpie.

However, I'm using constraints subdomain: 'api' in my routes and both curl and httpie don't like that. If I open Chrome and go to http://api.localhost:3000/v1/users, I receive a valid response. However, with httpie I get this error:

    http: error: ConnectionError: HTTPConnectionPool(host='api.localhost', port=3000): 
Max retries exceeded with url: /v1/users (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection 
object at 0x105732550>: Failed to establish a new connection: [Errno 8] 
nodename nor servname provided, or not known',)) while doing GET request to 
URL: http://api.localhost:3000/v1/users

I'm almost certin this is due to the subdomain but I can't find any documentation anywhere that refers to using subdomains with curl or httpie. How can I do this?


Solution

  • I figured it out! Here's what I did:

    Since I'm using a linux environment, I went to /etc/hosts and added a custom local host name called api.stevenlocal.com.

    In my Rails app in environments/development.rb I made sure the following line was set to 1:

     # Allow constraint subdomain for routes
      config.action_dispatch.tld_length = 1
    

    Setting it 1 tells rails that the top-level domain is going to be after one period (in this case, stevenlocal is the top-level domain and it is after .com). This is important because then Rails knows to look for my subdomain essentially after two periods (subdomain(first-period)top-level-domain(second-period)com). Rails by default has this line set to 1 but I had previously changed it.

    Now on the command line, when I try http api.stevenlocal.com:3000/v1/users, it works as expected. Note that http is a curl like command used with the httpie command line tool