Thursday, November 18, 2021

[SOLVED] Non variable recognition on Syspass API Bash Script

Issue

When i input a variable on the curl with the json indexed, it takes the string value of the variable, if i scaped the double-quotes, it returns me a sintax error because of in a json request u have to input the data with double-quotes. Example:

#!/bin/bash

token="x"
tokenPass="x"
name="prueba"
url="https://prueba.prueba.prueba"
user="prueba"
pass="prueba"
notes="prueba"

curl -k -H "Content-Type:Application/json" -d '{"jsonrpc": "2.0", "method": "account/create", "params": { "authToken": "$token", "tokenPass": "$tokenPass", "name": "$name" , "categoryId": "7", "clientId": "9","login":"$user","url": "$url" ,"pass": "$pass","notes": "$notes"}, "id": 1}' -o- https://syspass.prueba.es/api.php

The curl json request works if i input the data manually, but with the variables, when i create the account, the account is named as the string value of the variable, i mean, if the variable is named $name , the account created is name $name. Any help please? Also i tried to input the variable: "${variable}" and either works


Solution

I'd use jq to generate the JSON string (mostly, to handle the quoting for you, JSON strings are not trivial), and for readability (and for the sanity of the next maintainer) add some newlines and indentation:

data=$(
    jq  -n \
        --arg token "$token" \
        --arg tokenPass "$tokenPass" \
        --arg name "$name" \
        --arg url "$url" \
        --arg user "$user" \
        --arg pass "$pass" \
        --arg notes "$notes" \
        '{
            jsonrpc: "2.0",
            method: "account/create",
            params: { 
                authToken: $token,
                tokenPass: $tokenPass,
                name: $name,
                categoryId: "7",
                clientId: "9",
                login: $user,
                url: $url ,
                pass: $pass,
                notes: $notes
            },
            id: 1
        }'
)

curl -k \
     -H "Content-Type:Application/json" \
     -d "$data" \
     -o- \
     https://syspass.prueba.es/api.php


Answered By - glenn jackman