Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

Ruby get GET request data

General • Asked by jim

I'm making API endpoints and I'm having trouble getting the body of the request. Here is what I have:

In my routes I have set up an endpoint in my namespace:

namespace :api, :defaults => {:format => :json}  do
    resources :mainview do
        collection do
            get 'data'
        end
    end

In my front end I call the /api/mainview/data endpoint and pass it in a date inside of a json:

axios.get('/api/mainview/data', {"start_date":"2020-01-01"})
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log("We are getting this error:")
      console.log(error)
    });

And then, in my /api/mainview_controller.rb file, I got

module Api
    class MainviewController < AuthenticatedController
        def data
            puts "We are in the data function"
            #I want to print the body ({"start_date":"2020-01-01"}) of the request here 
        end
    end
end

So in this case, my API call seems to work as "We are in the data function" does get printed to the terminal. However, I don't know how to get the body or data from the request. If it's a post request I know I can use request.raw_post but I don't know what to use for GET requests. Most of the answers I found online are in PHP so any help would be great!


Jim,

You have to render a response through Rails. A puts is only going to print to the terminal. This doesn't work like PHP where it runs inside the HTML output, you have to actually build up the output in the response before Rails packages it up and sends it back.

If you're trying to render the URL params back out in the response, you would do:

def data
  render json: { 
      start_date: params[:start_date] 
    }
end

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 31,152+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.