jayteezer
jayteezer

Reputation: 115

How to insert a bash variable within GraphQL cURL POST request's JSON body

I've been spending hours trying to format my json post body so that my script is happy but I haven't had any luck. In my code down below, I would like to use the $utc_format variable as the value for datetime_gt key.

#!/bin/bash

utc_format=$(date -v-3d -v-5M -u +"%Y-%m-%dT%H:%M:%SZ")

curl \
    -X POST \
    -H "Content-Type: application/json" \
    -H "X-Auth-Email: [email protected]" \
    -H "X-Auth-key: $API_KEY" \
    --data '{"query": "query { viewer { zones ( filter: { zoneTag_in: [ \"abcde12345\" ] } ) { firewallEventsAdaptive ( filter: { source: \"waf\" datetime_gt: \"$utc_format\" ruleId: \"123456\" action: \"simulate\" } orderBy: [ datetime_DESC ] limit: 100 ) { clientIP edgeResponseStatus metadata { key value } } } } }"}' \
    https://api.api.com/ \
    | python -m json.tool >> curl_results

I even tried doing something like:

generate_post_data()
{
cat <<EOF
{
<json data>
}
EOF
}

but I got an error saying

"message": "failed to recognize JSON request: 'invalid character '\\n' in string literal'"

:'(

Thank you in advance!

Upvotes: 0

Views: 931

Answers (1)

Taylor G.
Taylor G.

Reputation: 711

The message literally means you have line break in your json body. Try removing line break to see if that helps.

curl \
    -X POST \
    -H "Content-Type: application/json" \
    -H "X-Auth-Email: [email protected]" \
    -H "X-Auth-key: $API_KEY" \
    --data "$(generate_post_data | tr -d '\n')" \
    https://api.api.com/ \
    | python -m json.tool >> curl_results

Upvotes: 1

Related Questions