PagerDuty REST API curl shorthand: a secure bash alias

rest-api

(Demitri Morgan) #1

Or: how to make quick and easy REST API requests from the command line

I often find myself needing to make various requests to the PagerDuty REST API to test and try things out. All the better when I can do it from the command line, because then it’s just a matter of piping the response to JQ to be able to pretty-print/pick apart/search through responses, or use the output to perform additional actions.

The following lives in a file sourced from my ~/.profile :

apicurl='curl -H "Accept: application/vnd.pagerduty+json;version=2;charset=utf8" -H "Content-Type: application/json;charset=utf8" -H "From: your-email-here@example.com"  '
# ...
alias pdtestcurl="$apicurl "'-H "Authorization: Token token=`gpg2 -d ~/path/to/your/api/key.asc`"'

The first part of the alias is declared as a variable to allow its reuse in other similar aliases that use other tokens for running API calls in other test accounts.

Example: get the user ID of a user matching a particular email address:

pdtestcurl 'https://api.pagerduty.com/users?query=user.mcuserson@example.com' | jq '.users[].id'

Notes/prerequisites:

  • You’ll need to have GPG2 installed, and store your API key in a PGP-encrypted file somewhere, and then put the path to it in the bash alias. Moreover, you’ll need a private key for decrypting the file set up.
  • If you trust the security of your system enough to leave plain text API keys on the file system, you can replace the command substitution part with simply cat [path-to-file] Don’t do this please; it’s a terrible idea :slight_smile:
  • Using single quotes around the part of the alias containing the command substitution prevents the command from running at the time that the alias is declared, so that the API key isn’t floating around in plain text inside of the alias definition.
  • Assuming you protect the private key with a passphrase: after a certain amount of time not using the alias (or your PGP key in general), you’ll be prompted to reenter your passphrase via pinentry. It’s like having one password to securely access your API keys.

(system) #2