1

I am having problem with grape. I have tried to look into their docs and google around. I could not find any solution or sample regarding this.

Let say I am sending this kind of format to the POST request of grape:

 {
    "preferences": {
        "play": {
            "weekdays": "5",
            "weekend": "8"
        },
        "grow": {
            "weekdays": "4",
            "weekend": "8"
        }
    }
}

Questions:

  1. How do I setup the Grape params to receive this post? I have tried something like this:
  params do
    optional :preferences, type: Hash  do
      optional :play do
        optional :weekdays
        optional :weekend
      end
      optional :grow, type: Hash do
        optional :weekdays
        optional :weekend
      end
    end
  end
  1. I am using postman to do the POST on my chrome. My question is, How do I set the Hash kind of params ? There are 3 options on postman which are form-data, form-urlencoded, and raw. I have tried with form-data and raw (json) it does not work for the raw json, it gave me an error saying that The requested content-type 'text/plain' is not supported

Any idea how do I fix these problems?

Thank you very much

kilua
  • 711
  • 1
  • 9
  • 16

1 Answers1

0

Answering question 1: If all parameters are optional then you don't even need the params block. Get rid of it and, for example, use params[:preferences][:play][:weekdays] to access the weekdays attribute. Just use the same idea to access other values.

Answering question 2: On Postman, use RAW but don't forget to set the header Content-Type to application/json. I've written the code below to play around with this example.

require 'grape'

class API < Grape::API
    version 'v1', :using => :header, :vendor => 'alienlabz', :format => :json
    format :json
    resource :preferences do
        post do
            puts params[:preferences][:play][:weekdays]
        end
    end
end

run API
Marlon
  • 888
  • 6
  • 12