BASH

Make HTTP Request and Parse JSON Response

Execute HTTP GET/POST requests using curl and parse the JSON response with `jq`, essential for interacting with web APIs directly from your bash scripts.

#!/bin/bash

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo "Error: jq is not installed. Please install it to parse JSON."
    echo "e.g., sudo apt-get install jq OR brew install jq"
    exit 1
fi

API_URL="https://jsonplaceholder.typicode.com/posts/1"

echo "Making GET request to: $API_URL"

RESPONSE=$(curl -s "$API_URL")

if [ $? -eq 0 ]; then
  echo "--- Raw JSON Response ---"
  echo "$RESPONSE" | jq .

  # Extract specific fields
  POST_TITLE=$(echo "$RESPONSE" | jq -r '.title')
  POST_ID=$(echo "$RESPONSE" | jq -r '.id')

  echo "--- Parsed Data ---"
  echo "Post ID: $POST_ID"
  echo "Post Title: $POST_TITLE"
else
  echo "Error: Failed to make HTTP request to $API_URL"
fi

# Example POST request (uncomment to use)
# POST_DATA='{"title": "foo", "body": "bar", "userId": 1}'
# POST_RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" -d "$POST_DATA" https://jsonplaceholder.typicode.com/posts)
# echo "
--- POST Response ---"
# echo "$POST_RESPONSE" | jq .
How it works: This script demonstrates how to make HTTP GET requests using `curl` and then parse the JSON response using `jq`. It includes a check for `jq` installation. This is invaluable for web developers who need to interact with REST APIs, fetch data, or test endpoints directly from the command line or within automated scripts (e.g., CI/CD tests).

Need help integrating this into your project?

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

Hire DigitalCodeLabs