This guide provides a robust Bash script to monitor your API's health by checking its status every minute. It ensures continuous availability and automatically alerts you if the service goes down, keeping your infrastructure running smoothly on Linux systems.
The Importance of Continuous API Monitoring
In modern web development, an Application Programming Interface (API) is the backbone of communication between services. If your API becomes unresponsive, it can lead to cascading failures across dependent applications, resulting in lost revenue and damaged user trust. While cloud providers offer basic uptime guarantees, they do not always provide granular, real-time visibility into the specific health endpoints of your custom services. A dedicated monitoring script allows you to detect issues immediately, rather than waiting for users to report problems or for automated billing cycles to reveal outages.
Implementing a simple, lightweight monitoring solution ensures that you maintain control over your service's availability. By checking the API's status at regular intervals, you can identify transient errors, network congestion, or server crashes before they escalate into major incidents. This proactive approach is essential for maintaining high availability SLAs (Service Level Agreements) and ensuring a seamless experience for end-users.
Setting Up the Monitoring Script
To create an effective monitor, we will use standard Linux tools available in most distributions, specifically curl for HTTP requests and bash for scripting logic. The script will perform the following actions: send a GET request to your API endpoint, check the HTTP response code, and log the result or trigger an alert if the status is not 200 OK.
First, create a new file named api_monitor.sh. Open this file in your preferred text editor and add the following configuration variables. Replace YOUR_API_URL with the actual endpoint you wish to monitor, such as https://api.example.com/health.
#!/bin/bash
# Configuration
API_URL="YOUR_API_URL"
CHECK_INTERVAL=60 # Seconds between checks
LOG_FILE="/var/log/api_monitor.log"
ALERT_EMAIL="[email protected]"
# Function to check API status
check_api() {
# Perform HTTP GET request and capture the HTTP code
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$API_URL")
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
if [ "$HTTP_CODE" -eq 200 ]; then
echo "$TIMESTAMP - API Status: OK (Code: $HTTP_CODE)" >> "$LOG_FILE"
else
echo "$TIMESTAMP - API Status: FAILED (Code: $HTTP_CODE)" >> "$LOG_FILE"
# Send email alert if failed
echo "API Down! Code: $HTTP_CODE" | mail -s "API Alert" "$ALERT_EMAIL"
fi
}
# Main loop
while true; do
check_api
sleep $CHECK_INTERVAL
done
This script uses curl with the -s flag for silent mode, -o /dev/null to discard the body, and -w "%{http_code}" to output only the HTTP status code. This minimizes bandwidth usage and processing time. If the status code is not 200, it logs the failure and sends an email notification using the mail command. Ensure that your system has the mailutils package installed and configured to send emails properly.
Scheduling with Cron
While the script above runs in an infinite loop, managing it via systemd or cron is often more reliable for production environments. Using cron allows the system scheduler to handle restarts if the script crashes. To set up the cron job, open your crontab by running crontab -e and add the following line:
* * * * * /path/to/api_monitor.sh
This configuration runs the script every minute. However, note that the internal sleep command in the script also dictates the interval. For better efficiency, you might prefer to remove the while true loop from the script and let cron handle the frequency. In that case, modify the script to run check_api once and exit, allowing cron to trigger it every minute. This reduces resource overhead since the script does not stay resident in memory.
If you need to run the script without elevated privileges, refer to our guide on Running Programs Without Using Sudo: A Tech Support Guide to ensure proper permissions are set for the log files and execution rights.
Logging and Maintenance
Proper logging is crucial for debugging. The script appends entries to /var/log/api_monitor.log. You should configure log rotation using logrotate to prevent this file from consuming excessive disk space over time. Create a configuration file at /etc/logrotate.d/api_monitor with the following content:
/var/log/api_monitor.log {
daily
rotate 7
compress
missingok
notifempty
}
This setup keeps seven days of compressed logs, ensuring you have historical data to analyze trends or investigate past outages. Regularly review these logs to identify patterns, such as intermittent failures during peak traffic hours, which might indicate capacity issues rather than code bugs.
Troubleshooting Common Issues
If the script reports false positives or fails to execute, check the following areas first. Ensure that the curl command works manually from the command line by running curl -s -o /dev/null -w "%{http_code}" YOUR_API_URL. If this returns an unexpected code, the issue may be related to SSL certificates, DNS resolution, or firewall rules blocking outbound connections.
Additionally, verify that the mail command is correctly configured. On some minimal Linux installations, the default MTA (Mail Transfer Agent) may not be set up. You can test email functionality by sending a test message to yourself. If you encounter permission denied errors when writing to the log file, ensure the user running the cron job has write access to the specified log directory. For more complex networking issues, such as SSH connection errors that might affect remote monitoring setups, see our article on Troubleshooting kex_exchange_identification Error in Linux SSH Connection.
Frequently Asked Questions
How can I receive notifications via Slack instead of email?
You can replace the mail command with a curl POST request to your Slack webhook URL. Simply update the alert section of the script to send a JSON payload containing the error message to the incoming webhook address provided by your Slack channel integration.
What should I do if my API requires authentication headers?
Modify the curl command in the script to include the -H "Authorization: Bearer YOUR_TOKEN" flag. This ensures that the health check request includes the necessary credentials to pass any authentication middleware protecting your API endpoint.
Can I monitor multiple APIs with this single script?
Yes, you can wrap the check_api function call in a loop that iterates through an array of URLs. Define each API URL in a variable list and call the check function for each one, ensuring distinct log entries or separate alert channels for each service to avoid confusion during incidents.
Why is my script consuming high CPU usage?
If you keep the while true loop with a very short sleep interval, it may spike CPU usage. Ensure the sleep duration matches your desired check frequency. Alternatively, switch to a cron-based execution model where the script runs once per minute and exits, which is much more efficient for the operating system.
How do I handle SSL certificate verification errors?
If your API uses a self-signed certificate, curl may fail by default. You can bypass verification by adding the -k or --insecure flag to the curl command, though this is less secure. Ideally, install the correct CA certificate in your system's trust store to allow secure verification without disabling checks.