2

I am trying to create a template that maps an array of ids from a query string param to a json template. I can't seem to figure out how to do it. This is what I have so far:

{
    "raw_ids_param_value": "$input.params('ids')",
    "mapped_ids": [
        #foreach($id in $input.params('ids'))
            {
                "id": "$id",
                "foo": "bar"
            }
            #if($foreach.hasNext),#end
        #end
    ]
}

When I make the request, you can see that the ids param is available, but it does nothing when I try to iterate over it:

GET /endpoint?ids=1,2,3
{
    "raw_ids_param_value": "1,2,3",
    "mapped_ids": [

    ]
}

What am I doing wrong?

1 Answer 1

4

Here is one solution: use .split(',') to split the string into an array.

{
    "mapped_ids": [
        #foreach($id in $input.params('ids').split(','))
            {
                "id": "$id",
                "foo": "bar"
            }
            #if($foreach.hasNext),#end
        #end
    ]
}

Result:

GET /endpoint?ids=1,2,3
{
    "mapped_ids": [
        {
            "id": "1",
            "foo": "bar"
        },
        {
            "id": "2",
            "foo": "bar"
        },
        {
            "id": "3",
            "foo": "bar"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest to decode the string before splitting by ',' since it is not a legal symbol for http URI: #foreach($id in $util.urlDecode($input.params('ids')).split(','))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.