BASH

Fetching Data from Web APIs with curl and Basic Text Parsing

Master fetching data from RESTful APIs using the `curl` command and perform basic text processing with `grep` and `sed` to extract specific information in Bash scripts.

#!/bin/bash

API_URL="https://api.github.com/zen" # A simple API that returns a plain text "zen" philosophy
OUTPUT_FILE="/tmp/api_response.txt"

echo "Fetching data from API: $API_URL"

# Fetch data using curl and save to a temporary file
# -s: silent mode (don't show progress meter or error messages)
# -o: write output to file instead of stdout
if ! curl -s "$API_URL" -o "$OUTPUT_FILE"; then
    echo "Error: Failed to fetch data from $API_URL" >&2
    exit 1
fi

echo "API response saved to $OUTPUT_FILE"

# Basic text parsing example: read the entire content
echo "--- Full API Response ---"
cat "$OUTPUT_FILE"
echo "--------------------------"

# For the GitHub Zen API, the response is the "zen" text itself
ZEN_MESSAGE=$(cat "$OUTPUT_FILE")
echo "GitHub Zen Message: \"$ZEN_MESSAGE\""

# Clean up temporary file
rm "$OUTPUT_FILE"
echo "Temporary file $OUTPUT_FILE removed."
How it works: This script demonstrates how to fetch data from a web API using `curl`. It fetches a plain text response from the GitHub Zen API and saves it to a temporary file. It then reads and displays the content of the file. Although `jq` is excluded from the broader topic, this example focuses on using `curl` for fetching and standard Bash utilities like `cat` for displaying or basic text manipulation, suitable for non-JSON or simple text responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs