Bash: how to format the JSON response of REST APIs

Bash: how to format the JSON response of REST APIs

In this article, we will see how to implement a Bash script that calls REST APIs and returns a formatted JSON output.

In the modern world of software development, interacting with REST APIs is a common need. REST APIs allow different systems to communicate with each other in a standardized way. In this article, we will see how to implement a Bash script that calls REST APIs and returns a formatted JSON output.

Before starting, make sure you have the following tools installed on your system:

  1. curl: A command-line tool for transferring data with URLs.
  2. jq: A command-line JSON processor that allows you to parse, filter, and transform JSON data.

To install curl and jq on a Debian-based system, you can use the following commands:


sudo apt-get update
sudo apt-get install curl jq

To start, let's define the variables needed for our API call. For example, the API URL and the specific endpoint we want to call:


API_URL="https://api.example.com/v1"
ENDPOINT="/data"

We use curl to make the API call. Let's say the API requires an authentication token, which we can pass as a header:


response=$(curl -s -H "Authorization: Bearer YOUR_ACCESS_TOKEN" "${API_URL}${ENDPOINT}")

The -s flag makes curl silent (suppresses progress meter), which makes the output cleaner.

We use jq to format the JSON output. Our goal is to make it readable:


formatted_response=$(echo "$response" | jq '.')

Finally, we print the formatted output:


echo "$formatted_response"

Let's put all the steps together:


#!/bin/bash

# Defining variables
API_URL="https://api.example.com/v1"
ENDPOINT="/data"
TOKEN="YOUR_ACCESS_TOKEN"

# Executing the API call
response=$(curl -s -H "Authorization: Bearer $TOKEN" "${API_URL}${ENDPOINT}")

# Check if the call was successful
if [ $? -eq 0 ]; then
    # Formatting JSON output
    formatted_response=$(echo "$response" | jq '.')
    # Displaying formatted output
    echo "$formatted_response"
else
    echo "Error in API call" >&2
fi

Conclusion

We have created a simple yet powerful Bash script to make calls to REST APIs and return formatted JSON output. This script can be easily extended to include additional functionality such as error handling, support for multiple HTTP methods (GET, POST, PUT, DELETE), and more complex parsing of JSON data. With curl and jq, you have powerful tools at your disposal to interact with APIs directly from the command line.