Ask A Question


You’re not receiving notifications from this thread.

Ruby get GET request data

jim asked in General

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'

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 => {
    .catch(error => {
      console.log("We are getting this 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 

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!



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] 
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.