BASH

Fetch and Parse JSON from an API with curl and jq

Learn to make HTTP GET requests to a REST API using `curl`, and efficiently parse the resulting JSON data on the command line using the powerful `jq` tool for data extraction.

#!/bin/bash

# Configuration
API_URL="https://jsonplaceholder.typicode.com/posts/1" # Example API endpoint

# Check for required commands
if ! command -v curl &> /dev/null; then
    echo "Error: 'curl' command not found. Please install it." >&2
    exit 1
fi

if ! command -v jq &> /dev/null; then
    echo "Error: 'jq' command not found. Please install it (e.g., sudo apt-get install jq)." >&2
    exit 1
fi

echo "Fetching data from: $API_URL"

# Make the API request and store the JSON response
RESPONSE=$(curl -s "$API_URL")

# Check if curl command was successful
if [ $? -ne 0 ]; then
  echo "Error: curl command failed." >&2
  exit 1
fi

# Check if the response is empty or potentially an error
if [ -z "$RESPONSE" ]; then
  echo "Error: Empty response from API." >&2
  exit 1
fi

echo "API Response (raw - first 5 lines):"
echo "$RESPONSE" | head -n 5

echo "
Parsing JSON with jq..."

# Parse specific fields using jq
POST_ID=$(echo "$RESPONSE" | jq -r '.id')
POST_TITLE=$(echo "$RESPONSE" | jq -r '.title')
POST_BODY_PREVIEW=$(echo "$RESPONSE" | jq -r '.body' | head -n 1)

# Display parsed data
if [ -n "$POST_ID" ]; then
  echo "  ID: $POST_ID"
  echo "  Title: $POST_TITLE"
  echo "  Body (first line): $POST_BODY_PREVIEW..."
else
  echo "Error: Could not parse ID from JSON response. Is the API_URL correct and returning valid JSON?" >&2
  exit 1
fi

echo "
API interaction complete."
How it works: This snippet demonstrates how to interact with a REST API from a Bash script. It first checks for the presence of `curl` and `jq` as prerequisites. It then uses `curl -s` to make a silent HTTP GET request to a specified `API_URL` and stores the JSON response in a variable. After basic error checking for the `curl` command and response content, it uses `jq -r` to parse specific fields (like `id`, `title`, `body`) from the JSON response, storing them in Bash variables for further processing or display. This is a fundamental pattern for automating API interactions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs