Nilesh Patil
Nilesh Patil

Reputation: 13

passing values with spaces in curl command using POST

I am trying to pass values with spaces in curl POST method. I am directing the values through a txt file. POST command does not allow me to pass values with spaces using the for while loop, But when i pass it without while loop it accepts the value without any error.

Below are the commands

This works perfectly fine

curl -d '{"name": "equity calculation support", "email": "[email protected]"}' -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Content-Type: application/json" -H "Accept: application/json" -X POST http://localhost:3000/api/teams
{"message":"Team created","teamId":103}

when using while loop and IFS it doesn't take the values with spaces:

while IFS= read -r line ; do curl -d '{"name": "'$line'"}' -H "Authorization: Basic YWRtaW46YWRtaW4=" -H "Content-Type: application/json" -H "Accept: application/json" -X POST 'http://localhost:3000/api/teams'; done < /tmp/group.txt

group.txt file contains the values .

Upvotes: 1

Views: 1656

Answers (1)

chepner
chepner

Reputation: 531055

You aren't quoting the expansion of $line:

while IFS= read -r line ; do
  curl -d '{"name": "'"$line"'"}' \ 
    -H "Authorization: Basic YWRtaW46YWRtaW4=" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -X POST 'http://localhost:3000/api/teams'
done < /tmp/group.txt

However, it's a better idea to let a tool like jq produce the JSON, to ensure that any characters in $line that need to be escaped to produce proper JSON do, indeed, get escaped.

while IFS= read -r line; do
  d=$(jq -n --argjson x "$line" '{name: $x}')
  curl -d "$d" ...
done < /tmp/group.txt

It looks like the JSON you want to create would fit on a single line, so you could also process all of /tmp/group.txt with a single call to jq, and pipe its output to your loop.

jq -c -R '{name: .}' | while IFS= read -r line; do
  curl -d "$line" ...
done

Upvotes: 2

Related Questions