All threads / Ruby get GET request data

Ask A Question

Notifications

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'
        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
Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.