Skip to main content

Example Bash program to retrieve and store a generated API access token, using curl and jq.

#!/usr/bin/env bash

# --------------------------------------------------------------------------
# Example: Store a generated API access token from JSON response using curl and jq
# json response == { "access_token":"some token value", "token_type": "Bearer", "expires": 9999 })
# Dependencies: curl, jq
# --------------------------------------------------------------------------

API_URI=https://example.com/api

CONSUMER_KEY="some consumer key"
CONSUMER_SECRET="some consumer secret"

AUTH_TOKEN=$(echo -n "${CONSUMER_KEY}:${CONSUMER_SECRET}" | base64)
ACCESS_TOKEN=''

generate_access_token() {
    local response

    response=$(curl --silent --show-error -k -d "grant_type=client_credentials" -H "Authorization: Basic ${AUTH_TOKEN}" "${API_URI}/token")

    if [[ $? -ne 0 ]] || [[ -z "${response}" ]]; then
        echo "Could not generate access token."
        return 1
    else
        ACCESS_TOKEN=$(printf %s "${response}" | jq -r ".access_token")
        if [[ $? -ne 0 ]] || [[ -z "${ACCESS_TOKEN}" ]]; then
            echo "Access token not found in response."
            return 1
        fi

        echo "Access token generated."
    fi
}