Skip to content

Instantly share code, notes, and snippets.

@fxg42
Last active April 9, 2021 11:41
Show Gist options
  • Save fxg42/00b1f7cfecac9af24644ac052dcc575b to your computer and use it in GitHub Desktop.
Save fxg42/00b1f7cfecac9af24644ac052dcc575b to your computer and use it in GitHub Desktop.
Bash script used to call HTTP/JSON api
#!/usr/bin/env bash
CURL=$(which curl)
if [[ ! -x "${CURL}" ]]; then
echo "Missing dependency. Please install curl (https://formulae.brew.sh/formula/curl):
$ brew install curl" 1>&2
exit 1
fi
readonly PROGRAM=$(basename -- $0)
method="POST"
hostname="localhost"
port="9200"
readonly USAGE="
USAGE: $PROGRAM [OPTIONS] <API PATH> [FILE]
Examples:
- POST a 'pre-invoice' to get totals:
$ $PROGRAM /api/invoice/totals ./prefacture.json
- GET the list of products:
$ $PROGRAM -m GET /api/product
- POST an invoice:
$ $PROGRAM /api/invoice ./facture.json
- POST a 'pre-invoice' to get totals, pretty print it
(requires jq, 'brew install jq') and store it in a file:
$ $PROGRAM /api/invoice/totals ./prefacture.json | jq > facture-with-totals.json
Options:
-h Displays this message.
-n <host name> Optional. Defaults to '$hostname'.
-p <port number> Optional. Defaults to '$port'.
-m <HTTP method> Optional. Defaults to '$method' Uses curl syntax."
OPTIND=1
while getopts ":hm:n:p:" opt; do
case $opt in
m ) method="${OPTARG}" ;;
n ) hostname="${OPTARG}" ;;
p ) port="${OPTARG}" ;;
h )
echo "${USAGE}"
exit 0 ;;
\?)
echo "Invalid option -${OPTARG}." 1>&2
echo "${USAGE}"
exit 1 ;;
esac
done
shift "$(( OPTIND - 1 ))"
readonly API_PATH=$1
if [[ -z "${API_PATH}" ]]; then
echo "Missing API path." 1>&2
echo "${USAGE}"
exit 1
fi
readonly FILE=$2
if [[ -z "${FILE}" && "${method}" == "POST" ]]; then
echo "Missing FILE." 1>&2
echo "${USAGE}"
exit 1
fi
$CURL -H 'Content-Type: application/json' \
-s \
-X "${method}" \
-d @"${FILE}" http://"${hostname}":${port}${API_PATH}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment