0

I have the following GET CURL from which I get an xml.

curl -X 'GET' \
  'http://local/something/something2' \
  -H 'accept: application/json' \
  -H 'authorization: auth'

Now I want to use the previous xml received above within this POST CURL:

curl -X 'POST' \
  'http://something/something2' \
  -H 'accept: application/json' \
  -H 'authorization: auth' \
  -H 'Content-Type: application/json' \
  -d '{
  "components": [
    {
      "locator": "sample",
      "config": xml file from above
    }
  ]
}'

How can I make the second CURL with POST?

  • Note that the details from your comment -- that you don't _directly_ get an XML file, but instead get a JSON file with an XML document in the `result` field -- are critical, and should be included in the question itself. – Charles Duffy Feb 10 '23 at 13:41

1 Answers1

0

See this post to see how to capture the output of the first command into a variable. Use it like this:


output=$(curl -X 'GET' \
  'http://local/something/something2' \
  -H 'accept: application/json' \
  -H 'authorization: auth')

# Assuming the $output variable is a JSON object, with a property
# called 'result', use 'jq' to extract the value of that property
result=$(jq -r '.result' <<< "$output")

# As noted above, escape the double quotes with backslashes
curl -X 'POST' \
  'http://something/something2' \
  -H 'accept: application/json' \
  -H 'authorization: auth' \
  -H 'Content-Type: application/json' \
  -d "{
  \"components\": [
    {
      \"locator\": \"sample\",
      \"config\": \"$result\"
    }
  ]
}"

Note the double quotes - double quotes must be there so $output variable can be used. As a result, the double quotes in the JSON need to be escaped.

hyperupcall
  • 869
  • 10
  • 21
  • Presumably you need quotes around `"$output"` too – tripleee Feb 10 '23 at 13:02
  • You're right, I forgot it said XML output and I assumed it was JSON – hyperupcall Feb 10 '23 at 13:04
  • You've been of great help with the variable, it works, but the whole POST CURL doesn't work, it says 405 Method Not Allowed, I'm guessing because when I echo my output variable it looks like this: {"valid":true,"errorMessage":null,"result":"\r\n – cojocaru robert Feb 10 '23 at 13:10
  • Yes, that's the issue! I have updated my answer in response - you need to use a tool called 'jq' to extract the JSON property – hyperupcall Feb 10 '23 at 13:37
  • You should also be using jq to escape the content to put it into the _new_ document. Substituting raw strings into JSON documents is not reliable: If that string contains literal quotes, newlines, or anything else that requires escaping, the result will be an invalid document. – Charles Duffy Feb 10 '23 at 13:38
  • Or you can take out the `-r` from where you're extracting `result` so the content _stays_ JSON and is in a form where it can be injected into another JSON document without further escaping. – Charles Duffy Feb 10 '23 at 13:40