Thursday, October 27, 2022

[SOLVED] How do I include POST request data with their respective url at the end of this script?

Issue

test_url() {
  local status=$(curl -o /dev/null -s -w "%{http_code}\n" -H "Authorization: token abc123" -H "Content-Type: application/json" --request POST -d '{"abc":"123", "xyz":"456"}' "$1")

  if [ "$status" = 200 ]; then
    echo "$2 is running successfully"
  else
    echo "Error at $2. Status code: $status"
  fi
}

test_url https://url_1.com url_1
test_url https://url_2.com url_2

What above script does is simply prints url_1 is running successfully or Error at url_2. Status code: 401, depending on the status code.

Let's say "abc":"123" is the POST request data for url_1 & "xyz":"456" for url_2. Similarly there may be lots of data and keeping it all in one line will be confusing. So I want to move the data to their respective url which are at the end. Something like:

test_url '{"abc":"123"}' https://url_1.com url_1
test_url '{"xyz":"456"}' https://url_2.com url_2

I know this is a wrong format, just wanted to give an example. So what's the correct way?


Solution

You can try this:

local status=$(curl -o /dev/null -s -w "%{http_code}\n" -H "Authorization: token abc123" -H "Content-Type: application/json" -d "$1" -X POST $2)

To call:

test_url '{"abc":"123"}' "https://url_1.com"


Answered By - Juranir Santos
Answer Checked By - Candace Johnson (WPSolving Volunteer)