BASH

Make HTTP Requests with Error Handling using Curl

Learn to perform robust HTTP GET requests using `curl` in Bash, including checking HTTP status codes for success or failure and handling network issues, useful for API health checks and simple integrations.

#!/bin/bash

# Target URL for the HTTP GET request
URL="https://example.com/api/health"

# Function to make an HTTP request and check status
check_url () {
  local url="$1"
  echo "Checking $url..."

  # Use curl to get the HTTP status code and the response body
  # -s: Silent mode, don't show progress meter or error messages
  # -o /dev/null: Discard the response body
  # -w "%{{http_code}}": Output only the HTTP status code
  # -L: Follow redirects
  HTTP_STATUS=$(curl -s -o /dev/null -w "%{{http_code}}" -L "$url")
  CURL_EXIT_CODE=$?

  if [ "$CURL_EXIT_CODE" -ne 0 ]; then
    echo "Error: curl failed with exit code $CURL_EXIT_CODE."
    echo "Possible network issue or invalid URL."
    return 1 # Indicate failure
  fi

  echo "HTTP Status Code: $HTTP_STATUS"

  # Check for success (2xx status codes)
  if [[ "$HTTP_STATUS" -ge 200 && "$HTTP_STATUS" -le 299 ]]; then
    echo "✅ Success: URL is reachable and responded with a 2xx status."
    return 0 # Indicate success
  elif [[ "$HTTP_STATUS" -ge 300 && "$HTTP_STATUS" -le 399 ]]; then
    echo "⚠️ Warning: URL responded with a 3xx redirect status. Check the final destination."
    return 0 # Indicate success for redirect, but with warning
  else
    echo "❌ Failure: URL responded with status code $HTTP_STATUS."
    return 1 # Indicate failure
  fi
}

# Example usage:
check_url "$URL"

if check_url "https://api.github.com/zen"; then
  echo "GitHub Zen API is up!"
else
  echo "GitHub Zen API might be down or unreachable."
fi
How it works: This Bash script provides a robust way to perform HTTP GET requests using `curl` and interpret the results. The `check_url` function takes a URL, executes `curl` in silent mode, discards the response body, and captures only the HTTP status code using `-w '%{http_code}'`. It also uses `-L` to follow redirects. Crucially, it checks `curl`'s exit code for network-level errors before evaluating the HTTP status. The function then categorizes the response into success (2xx), warning (3xx), or failure, making it ideal for API health checks or basic integration tests in automated scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs