Mr.D Mr.D - 5 months ago 19
JSON Question

Grape, sending JSON as params

My Grape API accepts json format and I have method that accepts JSON as parameter:

desc 'JSON test'
params do
requires :json, type: JSON
end
post :json_test do
json = params[:json]
{result: json}
end


When I make request via postman, parameters are raw with application/json content type:

{
"json": {"test": "test"}
}


When I send this I get error message:

"json is invalid"


However, when I send it like this:

{
"json": "{\"test\": \"test\"}"
}


It shows me correct response:

{
"result": {
"test": "test"
}
}


Why this is happening? When I make type
Hash
the first variant works, but if I want to send
Array
of hashes/jsons? I kniw that Grape does not support
Array[Hash]
type.

Answer

grape parses the application/json data before it reaches your params block.


in this block:

params do
  requires :json, type: JSON
end

you are telling grape that your :json param should contain a JSON string.

so when you send this:

{
   "json": {"test": "test"}
}

json contains

{"test": "test"} 

which is sees as a hash, not a valid JSON string hence our error.

but when you send this

{
  "json": "{\"test\": \"test\"}"
}

json contains

"{\"test\": \"test\"}"

which is a valid JSON string, which it will then happily parse into a hash for you.


If you want to use

{
   "json": {"test": "test"}
}

in your post request, Your params block should be something like this:

params do
    requires :json, type: Hash #<-- Hash here instead of JSON since json data has already been parsed into a Hash
end
Comments