BASH

Implement a Basic Web Service Health Check Script

Create a simple Bash script to check the availability and HTTP status code of a web service or API endpoint using `curl`, crucial for monitoring.

#!/bin/bash
URL="https://example.com/api/health"
EXPECTED_STATUS=200
TIMEOUT_SECONDS=5

echo "Checking health of $URL..."

HTTP_STATUS=$(curl -s -o /dev/null -w "%{\http_code}" --connect-timeout "$TIMEOUT_SECONDS" "$URL")

if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
  echo "SUCCESS: Web service is healthy (HTTP Status: $HTTP_STATUS)"
  exit 0
else
  echo "ERROR: Web service is UNHEALTHY (HTTP Status: $HTTP_STATUS). Expected $EXPECTED_STATUS."
  exit 1
fi
How it works: This script performs a basic health check on a web service or API endpoint. It uses `curl` to fetch the HTTP status code without downloading the full response body (`-s -o /dev/null -w "%{\http_code}"`). The script then compares the retrieved status code with an `EXPECTED_STATUS` and reports success or failure, exiting with appropriate status codes for use in automated systems. A `TIMEOUT_SECONDS` is included for robustness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs