Bash API Client

The Bourne Again SHell or BASH is a common shell available on unix-like systems. It is useful as an every day command interpreter, and also provides the ability to write scripts.

To illustrate how accessible our API is, we chose to write a BASH script that acts as an API client for SmartFile. You can download the fully working script here.

smartfileapi.sh

#!/bin/bash

# These constants are needed to access the API.
API_URL="http://app.smartfile.com/api/1"
API_KEY="api-key"
API_PWD="api-password"

# We will use the cURL program to perform our HTTP request.
CURL=$(which curl)

# Make sure cURL exists and is executable.
if [ ! -x ${CURL} ]; then
    echo "You must have curl installed to use this API client."
    exit 1
fi

# A little function to ask the user a question, then assign their
# response into the provided global variable name.
function prompt() {
    local __return=$1
    local __result
    echo -n "$2"
    read __result
    eval $__return="'$__result'"
}

# Ask the user for the info we need.
prompt FULLNAME "Please enter a full name: "
prompt USERNAME "Please enter a username: "
prompt PASSWORD "Please enter a password: "
prompt EMAIL "Please enter an email address: "

# Build the full URL to the User add API.
URL="${API_URL}/users/add/"

# Use cURL to make the HTTP request. The output of this request
# as well as the HTTP status code will be printed to stdout.
OUTPUT=`${CURL} ${URL} --data-urlencode name=${FULLNAME} --data-urlencode username=${USERNAME} \
    --data-urlencode password=${PASSWORD} --data-urlencode email=${EMAIL} \
    --user-agent "BASH SmartFile API Sample Client" --user ${API_KEY}:${API_PWD} --silent --write-out "\n%{http_code}\n"`

# Do some parsing to separate the last line of output from the
# rest of the output. The last line is the HTTP status code.
ERROR=""
HTTP_STATUS=""
while read -ra LINES; do 
    for LINE in "${LINES[@]}"; do
        if [ ! "${HTTP_STATUS}" == "" ]; then
            ERROR="${ERROR} ${HTTP_STATUS}"
        fi
        HTTP_STATUS=$LINE
    done 
done <<< "${OUTPUT}"

# Now, attempt to retrieve the JSON encoded error message.
MESSAGE=$(echo -n "${ERROR}" grep message | cut -d\" -f4)

# Otherwise fail back to the entire server response.
if [ -z "${MESSAGE}" ]; then
    MESSAGE=${ERROR}
fi

# Check for success, print error message on failure.
if [ "${HTTP_STATUS}" == "201" ]; then
    echo "Successfully created user ${USERNAME}."
else
    echo "Error creating user ${USERNAME}: ${MESSAGE}."
fi