Monitor API Status

Abstract: Automate continuous API health checks and receive email alerts on Linux when the service returns non-200 HTTP status codes.

Created: 2026-09-30 by

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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More