BASH
Execute Authenticated HTTP Requests with cURL
Perform advanced HTTP requests in Bash using 'curl', including sending custom headers, JSON bodies, and handling authentication for API interactions.
#!/bin/bash
API_BASE_URL="https://api.example.com"
AUTH_TOKEN="your_secure_auth_token_123"
# --- GET request with Authorization header ---
echo "Fetching items (GET request with Auth header):"
curl -s -X GET \
-H "Authorization: Bearer $AUTH_TOKEN" \
"$API_BASE_URL/items"
echo "
----------------------------------------"
# --- POST request with JSON body and custom headers ---
JSON_PAYLOAD='{"name":"New Product","price":29.99,"currency":"USD"}'
echo "Creating new product (POST request with JSON body):"
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AUTH_TOKEN" \
-d "$JSON_PAYLOAD" \
"$API_BASE_URL/products/create"
echo "
----------------------------------------"
# --- GET request to check status, showing response headers ---
echo "Checking API status (GET request showing headers):"
curl -svo /dev/null \
-H "Authorization: Bearer $AUTH_TOKEN" \
"$API_BASE_URL/status" 2>&1 | grep '< HTTP'
How it works: This snippet illustrates how to leverage `curl` for more complex API interactions than just basic GET requests. It demonstrates how to send an `Authorization: Bearer` token in the request header for authenticated API calls. Furthermore, it shows how to perform a POST request, including setting the `Content-Type` header to `application/json` and sending a JSON payload using the `-d` (data) option. The last example shows how to view response headers, which is useful for debugging.