boxes-api/scripts/gem_script.bash

71 lines
1.6 KiB
Bash
Executable File

#!/bin/bash
# API base URL
API_BASE_URL="http://localhost:8080/api/v1"
# Login credentials
USERNAME="boxuser"
PASSWORD="boxuser"
# Usage message
usage() {
echo "Usage: $0 -m <method> -e <endpoint> [-i <id>] [-d <data>]"
echo " -m <method> HTTP method (GET, POST, PUT, DELETE)"
echo " -e <endpoint> API endpoint (e.g., /tags/1/items)"
echo " -i <id> Optional element ID (appended to endpoint)"
echo " -d <data> Optional data (for POST/PUT requests)"
exit 1
}
# Parse command line options
while getopts ":m:e:i:d:" opt; do
case $opt in
m) method="$OPTARG" ;;
e) endpoint="$OPTARG" ;;
i) id="$OPTARG" ;;
d) data="$OPTARG" ;;
\?) usage ;;
esac
done
# Check if required options are provided
if [[ -z "$method" || -z "$endpoint" ]]; then
usage
fi
# Construct the URL
url="$API_BASE_URL$endpoint"
if [[ -n "$id" ]]; then
url="$url/$id"
fi
# Function to make an authenticated request
function authenticated_request() {
local method=$1
local url=$2
local data=$3
# Get a new JWT token
TOKEN=$(curl -s -X POST -H "Content-Type: application/json" \
-d "{\"username\":\"$USERNAME\", \"password\":\"$PASSWORD\"}" \
"$API_BASE_URL/login" | jq -r '.token')
# Make the authenticated request
curl -s -X "$method" -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "$data" \
"$url"
}
# Make the API request
response=$(authenticated_request "$method" "$url" "$data")
echo "Raw response: $response"
# Check if the request was successful
if [[ $? -eq 0 ]]; then
# Pretty print the response using jq
echo "$response" | jq .
else
echo "Error: Failed to make API request."
fi