BASH
HTTP Requests and JSON Parsing
Learn how to make basic HTTP GET requests using `curl` and parse the JSON response effectively with `jq` in your Bash scripts for API interactions.
#!/bin/bash
API_URL="https://jsonplaceholder.typicode.com/posts/1"
response=$(curl -s "$API_URL")
if [ $? -eq 0 ] && [ -n "$response" ]; then
echo "API Response (Raw):"
echo "$response" | jq .
echo "
Title:"
echo "$response" | jq -r '.title'
echo "
User ID:"
echo "$response" | jq -r '.userId'
else
echo "Failed to fetch data from $API_URL or response was empty."
fi
How it works: This script fetches data from a specified API endpoint using `curl -s` (silent mode to suppress progress meter). It then checks if the `curl` command was successful (exit code 0) and if the response is not empty. If valid, it pipes the raw JSON response to `jq` for pretty-printing (`jq .`) and extracts specific fields like `title` and `userId` using `jq -r '.key'` for raw output, making it easy to interact with APIs from the command line.