BASH
Send JSON Webhook Notifications with `curl`
Learn to send custom JSON webhook payloads using `curl` in Bash, perfect for integrating scripts with chat services, CI/CD pipelines, or monitoring tools.
#!/bin/bash
WEBHOOK_URL="https://example.com/your/webhook/endpoint"
MESSAGE="Hello from your Bash script!"
STATUS="success"
# You can customize the payload based on your webhook service requirements
JSON_PAYLOAD='{
"text": "'$MESSAGE'",
"status": "'$STATUS'",
"timestamp": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'",
"script_name": "'$(basename "$0")'"
}'
echo "Sending webhook notification..."
# Use curl to send a POST request with the JSON payload
# -X POST: Specifies the HTTP method as POST
# -H "Content-Type: application/json": Sets the header to indicate JSON data
# -d "$JSON_PAYLOAD": Specifies the data to send in the request body
# -s: Silent mode (don't show progress meter or error messages)
# -o /dev/null: Discard output to stdout
curl -X POST \
-H "Content-Type: application/json" \
-d "$JSON_PAYLOAD" \
-s -o /dev/null \
"$WEBHOOK_URL"
# Check the exit status of curl
if [ $? -eq 0 ]; then
echo "Webhook sent successfully!"
else
echo "Failed to send webhook. Curl exited with error code $?."
# You might want to log the error or retry
fi
# Example for Slack (replace with your actual Slack webhook URL)
# SLACK_WEBHOOK_URL="https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
# SLACK_PAYLOAD='{"text": "Deployment to production complete! :rocket: Status: Success."}'
# curl -X POST -H 'Content-type: application/json' --data "$SLACK_PAYLOAD" $SLACK_WEBHOOK_URL
How it works: This snippet demonstrates how to send a JSON webhook notification using the `curl` command. It constructs a JSON payload with dynamic values like a message, status, and timestamp. `curl` is then used with specific flags: `-X POST` sets the HTTP method, `-H "Content-Type: application/json"` ensures the server interprets the data correctly, and `-d "$JSON_PAYLOAD"` sends the JSON as the request body. The `-s -o /dev/null` flags are used to suppress `curl`'s output, making the script cleaner. Checking `$?` after the `curl` command allows you to determine if the request was successful, enabling error handling or logging.