Grady Ela Grady Ela - 1 month ago 8
JSON Question

cURL POST request using variables

I am trying to set up a basic code to insert some customers into a our customer support software without having to go in and do each one manually.
I seem to be having issues when I introduce variables into the code.

This code works:

#!/bin/sh
curl https://yoursite.desk.com/api/v2/customers \
-u username:password \
-X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"first_name":"John",
"last_name":"Doe",
"phone_numbers":
[
{
"type":"Other",
"value":"5555555555"
}
],
"emails":
[
{
"type": "other",
"value":"johndoe@email.com
}
],
"custom_fields":
{
"field_a":"12345"
}
}'


This code always returns the error 'invalid JSON'

#!/bin/sh

first=John
last=Doe
phone=5555555555
phone_type=other
email=johndoe@email.com
email_type=other
id=12345

curl https://yoursite.desk.com/api/v2/customers \
-u username:password \
-X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"first_name":'"$first"',
"last_name":'"$last"',
"phone_numbers":
[
{
"type":'"$phone_type"',
"value":'"$phone"'
}
],
"emails":
[
{
"type":'"$email_type"',
"value":'"$email"'
}
],
"custom_fields":
{
"field_a":'"$id"'
}
}'


For what it's worth, as I have been tweaking the code occasionally the error code will display "emails": "value": (invalid) and "phone_numbers":"value":(invalid)

Answer

In your example "$first" is expanded to John (the double quotes are lost). The same goes for the other expansions. Include the required double quotes in the single quoted part of your command (but preserve the double quotes around the variable expansions):

#!/bin/sh

first=John
last=Doe
phone=5555555555
phone_type=other
email=johndoe@email.com
email_type=other
id=12345

curl https://yoursite.desk.com/api/v2/customers \
-u username:password \
-X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
    "first_name":"'"$first"'",
    "last_name":"'"$last"'",
    "phone_numbers":
      [
        {
          "type":"'"$phone_type"'",
          "value":"'"$phone"'"
        }
      ],
    "emails":
      [
        {
          "type":"'"$email_type"'",
          "value":"'"$email"'"
        }
      ],
    "custom_fields":
      {
          "field_a":"'"$id"'"
      }
    }'