Skip to content

Instantly share code, notes, and snippets.

@ptaylor
Created November 1, 2024 11:23
Show Gist options
  • Save ptaylor/1d63a5619b5acc153bd955d5f300f089 to your computer and use it in GitHub Desktop.
Save ptaylor/1d63a5619b5acc153bd955d5f300f089 to your computer and use it in GitHub Desktop.
Generic curl request script for JSON REST APIs
#!/bin/sh
#
# Usage: curl-request METHOD PATH [DATA]
#
if [ "${XXX_TOKEN}" == "" ]; then
echo "Set XXX_TOKEN"
exit 1
fi
API_VERSION=2022-11-28
API_ENDPOINT="https://api.xxxxx.com"
VERBOSE=--verbose
VERBOSE=
CURL_METHOD=$1
CURL_PATH=$2
CURL_DATA=$3
CURL_OUTPUT="status: %{http_code}\ntime: %{time_total}"
ENDPOINT="${API_ENDPOINT}/${CURL_PATH}"
CURL_METHOD=`echo $CURL_METHOD | tr a-z A-Z`
if [ -t 1 ] ; then
echo "${CURL_METHOD} ${ENDPOINT}"
if [ ! -z "${CURL_DATA}" ]; then
echo "request:"
if echo "${CURL_DATA}" | jq empty > /dev/null 2>&1 ; then
echo "${CURL_DATA}" | jq
else
echo "${CURL_DATA}"
fi
echo ""
fi
fi
RESPONSE=/tmp/curl-response.$$
CURL_STATUS=/tmp/curl-status.$$
trap "rm -f \"${RESPONSE}\" \"${CURL_STATUS}\"" EXIT
curl \
-s \
--write-out "${CURL_OUTPUT}" \
${VERBOSE} \
-X ${CURL_METHOD} \
-H "Authorization: token ${API_TOKEN}" \
-H "Accept: application/vnd.github+json" \
-H "X-Api-Version: ${API_VERSION}" \
--data "${CURL_DATA}" \
-o "${RESPONSE}" \
${ENDPOINT} \
> "${CURL_STATUS}"
status=`cat ${CURL_STATUS}`
if [ -t 1 ]; then
echo "${status}"
echo "response:"
fi
if jq empty "${RESPONSE}" > /dev/null 2>&1 ; then
cat "${RESPONSE}" | jq
else
cat "${RESPONSE}"
fi
#!/bin/sh
#
# Usage: post-request RESOURCE NAME VALUE
#
NAME=${2-default}
VALUE=${3-1234}
DATA=`cat << __EOM__
{
"name": "${NAME}",
"value": "${VALUE}",
"active": true
}
__EOM__
`
./curl-request POST foobar/$1/resources "${DATA}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment