BASH

Interact with REST APIs using cURL and Parse JSON with jq

Learn to make authenticated GET and POST requests to REST APIs using `curl` and effectively parse the JSON responses with `jq` in your bash scripts for automation.

#!/bin/bash

# --- Configuration ---
API_BASE_URL="https://jsonplaceholder.typicode.com"
AUTH_TOKEN="your_auth_token" # Replace with your actual token if needed

# --- Function to make a GET request ---
function get_data {
    local endpoint="$1"
    echo "[$(date)] Making GET request to $API_BASE_URL/$endpoint..."
    curl -s -H "Authorization: Bearer $AUTH_TOKEN" "$API_BASE_URL/$endpoint"
}

# --- Function to make a POST request ---
function post_data {
    local endpoint="$1"
    local payload="$2"
    echo "[$(date)] Making POST request to $API_BASE_URL/$endpoint with payload: $payload..."
    curl -s -X POST \
         -H "Content-Type: application/json" \
         -H "Authorization: Bearer $AUTH_TOKEN" \
         -d "$payload" \
         "$API_BASE_URL/$endpoint"
}

# --- Script Logic ---

echo "--- Fetching all posts ---"
POSTS_RESPONSE=$(get_data "posts")

# Check if jq is installed
if ! command -v jq &> /dev/null
then
    echo "jq could not be found. Please install it to parse JSON responses."
    echo "(e.g., sudo apt-get install jq or sudo yum install jq)"
    exit 1
fi

# Parse and display first 3 post titles using jq
echo "First 3 post titles:"
echo "$POSTS_RESPONSE" | jq -r '.[0:3] | .[] | .title'

echo "
--- Fetching a single post by ID (e.g., post ID 1) ---"
SINGLE_POST_RESPONSE=$(get_data "posts/1")
echo "Post ID 1 Title: $(echo "$SINGLE_POST_RESPONSE" | jq -r '.title')"

echo "
--- Creating a new post (POST request) ---"
NEW_POST_PAYLOAD='{"title": "foo", "body": "bar", "userId": 1}'
NEW_POST_RESPONSE=$(post_data "posts" "$NEW_POST_PAYLOAD")

echo "New post created with ID: $(echo "$NEW_POST_RESPONSE" | jq -r '.id')"

echo "
Script finished."
How it works: This script demonstrates how to interact with REST APIs using `curl` for making HTTP requests and `jq` for parsing the resulting JSON data. It includes examples for both authenticated GET and POST requests, showing how to set headers and send JSON payloads. The `jq` utility is then used to extract specific fields from the JSON response, making it incredibly powerful for automating tasks that involve web APIs. Ensure `jq` is installed on your system for parsing functionality.

Need help integrating this into your project?

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

Hire DigitalCodeLabs