Search code examples
ruby-on-railsrubyhashruby-grapegrape-api

How to pass a Hash to Grape API method?


I'm having problems with the Grape gem and the parameters validation. The idea behind this is to create a complex entity using nested attributes through an API service.

I have a method to create a trip, trip have many destinations and i want to pass that destinations using a hash (using the accepts_nested_attributes_for helper).

I have this grape restriction over the parameter:

requires :destinations, type: Hash

And I'm trying to send something like this:

{ destinations => [ 
  { destination: { name => 'dest1'} },
  { destination: { name => 'dest2'} }, 
  { destination: { name => 'dest3'} }
]}

In order to build something like the structure below inside the method and get the trip created:

{ trip: {
  name: 'Trip1', destinations_attributes: [
    { name: 'dest1' },
    { name: 'dest2' },
    { name: 'dest3' }
  ]
}}

I'm using POSTMAN chrome extension to call the API method.

Here's a screen capture: enter image description here

If someone can help me i would be very grateful.


Solution

  • By the looks of what you are trying to send, you need to change the Grape restriction, because destinations is an Array, not a Hash:

    requires :destinations, type: Array
    

    You don't need the "destination" hash when sending the request:

    { destinations => [ 
      { name => 'dest1', other_attribute: 'value', etc... },
      { name => 'dest2', other_attribute: 'value', etc... }, 
      { name => 'dest3', other_attribute: 'value', etc... }
    ]}
    

    This creates an Array of hashes.

    In order to send this through POSTMAN, you'll need to modify that destinations param your sending and add multiple lines in POSTMAN. Something like:

    destinations[][name]                'dest1'
    destinations[][other_attribute]     'value1'
    destinations[][name]                'dest2'
    destinations[][other_attribute]     'value2'
    destinations[][name]                'dest3'
    destinations[][other_attribute]     'value3'
    

    Hope this answers your questions. Let me know if this is what you were looking for.