BraveVN
BraveVN

Reputation: 430

Rails - Array of hashes in Grape API

I'm really a new guy to Rails, in my project I want to submit a JSON string to Grape API. As you can see, my JSON has an user array that contains many objects. How can I define it in my Grape ?
Thank you

{
    "users":[
        {
            "first_name":"Brittany",
            "last_name":"Chen",
            "email":"[email protected]",
            "phone_number":"+29-46-957-15423"
        },
        {
            "first_name":"Lynn",
            "last_name":"Brooks",
            "email":"[email protected]",
            "phone_number":"+84-95-185-00137"
        },
        {
            "first_name":"Claire",
            "last_name":"Paul",
            "email":"[email protected]",
            "phone_number":"+66-64-893-53401"
        },
        {
            "first_name":"Gemma",
            "last_name":"Carter",
            "email":"[email protected]",
            "phone_number":"+83-46-325-54538"
        }
    ],
    "service_ids":["1", "2", "3"],
    "auth_token":"xxxxxxxxxxxxxxxxxxxxxx"
}

this is my Grape params

params do
    optional :user, type: Hash do
        optional :email, type: String, desc: "user email"
        optional :first_name, type: String, desc: "user first name"
        optional :last_name, type: String, desc: "user last name"
        optional :phone_number, type: String, desc: "user phone number"
    end
    optional :service_ids, type: Array[Integer], desc: "list of service ids selected"
    requires :auth_token, type: String, desc: "authentication_token"
end

Upvotes: 1

Views: 2938

Answers (1)

Péha
Péha

Reputation: 2933

This is called "Validation of nested parameters" in Grape. In your code, you were actually asking for a user hash containing optional parameters email, first_name, last_name and phone_number, so not exactly what you were looking for.

With a block, group, requires and optional accept an additional option type which can be either Array or Hash, and defaults to Array. Depending on the value, the nested parameters will be treated either as values of a hash or as values of hashes in an array.

Source: https://github.com/ruby-grape/grape#validation-of-nested-parameters

So in your case, you would have to describe your params like this :

params do
  optional :users, type: Array do
    optional :email,        type: String, desc: "user email"
    optional :first_name,   type: String, desc: "user first name"
    optional :last_name,    type: String, desc: "user last name"
    optional :phone_number, type: String, desc: "user phone number"
  end
  # ...
  # any other params
  # ...
end

And so each item in the array will be expected to match the fields in the given block.

Upvotes: 2

Related Questions