Home > Mobile >  Checking curl response code and returning results from inside a bash function
Checking curl response code and returning results from inside a bash function

Time:11-11

I have a bash script that makes a ton of RESTful HTTP calls (via curl) to the many different endpoints of the same service. I want to write a bash function that makes a configurable curl request and verifies that the status is HTTP 200. If its not, the entire script should exit with an error code. If it is, the function should return the JSON that is returned by the HTTP response coming back from the REST API.

My best attempt thus far is:

function callServer() {

  payload=$1

  curl --request POST \
    --url https://myservice.example.com \
    --header 'Authorization: $API_KEY' \
    --header 'Content-Type: application/json' \
    --data '$payload' > jsonResp

}

An example usage from inside the script might be:

$getWidgetsJson=callServer '{"flim":"flam"}'

or:

$launchMissiles=callServer '{"fizz":"buzz","num":50}'

I think I'm close but having trouble seeing the forest through the trees here. How can I check 200-status on the response in the curl, and either fail the script or return the JSON from the function accordingly?

CodePudding user response:

You could use:

  1. --output option to specify your output filename
  2. --write-out option to get HTTP code response

Like this:

#! /bin/bash

function callServer() {

  local API_KEY="$1"
  local PAYLOAD="$2"
  local OUTPUT_FILENAME="$3"
  local -n HTTP_RESPONSE_CODE="$4"

  HTTP_RESPONSE_CODE=$(curl --request POST \
    --url https://myservice.example.com \
    --header "Authorization: ${API_KEY}" \
    --header 'Content-Type: application/json' \
    --data "${PAYLOAD}" \
    --output "${OUTPUT_FILENAME}" \
    --write-out "%response_code" \
  )

}

declare HTTP_CODE=
callServer "theApikey" '{"flim":"flam"}' "theOutputFileName" HTTP_CODE

echo "The HTTP code is ${HTTP_CODE}"
echo "Filename content:"
cat theOutputFileName
echo "."

  • Related