BASH

Make HTTP Request and Extract JSON Field with jq

Effortlessly make HTTP GET requests to API endpoints using `curl` and parse JSON responses with `jq` to extract specific data fields, useful for scripting API interactions.

#!/bin/bash

# Check if jq is installed
if ! command -v jq &> /dev/null
then
    echo "jq is not installed. Please install it to use this script."
    echo "On Debian/Ubuntu: sudo apt-get install jq"
    echo "On macOS: brew install jq"
    exit 1
fi

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

echo "Making request to: $API_URL"

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

if [ $? -ne 0 ]; then
  echo "Error: curl command failed."
  exit 1
fi

EXTRACTED_VALUE=$(echo "$RESPONSE" | jq -r "$FIELD_TO_EXTRACT")

if [ $? -ne 0 ]; then
  echo "Error: jq command failed, check FIELD_TO_EXTRACT or JSON format."
  echo "Raw response: $RESPONSE"
  exit 1
fi

echo "Extracted '$FIELD_TO_EXTRACT': $EXTRACTED_VALUE"
How it works: This script demonstrates how to make an HTTP GET request using `curl` and then parse the JSON response to extract a specific field using `jq`. It includes a check for `jq` installation and error handling for both `curl` and `jq` commands, making it robust for API interaction and data extraction tasks within shell scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs