Home > OS >  backtick " ` " in request body in bash shell script while calling CURL
backtick " ` " in request body in bash shell script while calling CURL

Time:02-11

I'm writing CURL COMMAND

HTTP_Method : POST

API : api/databricks/query

Request body  {"query":" GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

The query,I have execute using POSTMAN it's working

curl --location --request POST 'https://<databick_workspace-url>/api/sql/databricks/query' \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID` " }
# Working, And user can access DB

I believe the problem is with backticks,

// Function 
function grantReadAccess() {
  local path="/api/sql/databricks/query"
  local url="https://<databricks-workspace-url>/${path}"
  printf 'curl %q' "${url}"
  local DATABASENAME="DB-NAME"
  local userID="userID"

  local content="GRANT SELECT,READ_METADATA,USAGE on DATABASE \`${DATABASENAME}\` to \`${userID}\` "
  echo "------------$content" 
  // OUTPUT Here : GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB-NAME` to `userID`
  // Same I have to pass in request body
  local permissionToGroup=$(
    curl -X POST "${url}" -H "Authorization: Bearer ${authtoken}" -H "Content-Type: application/json" -d '{ "query": \"'"${content}"'\" } ')
    //Required in this {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE `DB` to `userID` " }

  echo "${permissionToGroup}"
}

// Tried In Postman insted of using backtick
 1. Single Quote "'" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE 'DB' to 'userID' "
 2. Blacket "(" {"query":"GRANT SELECT,READ_METADATA,USAGE on DATABASE (DB) to (userID) "

Error

{
  "query": "grant SELECT, READ_METADATA, USAGE on DATABASE 'DB' to 'useID' ",
    "data": null,
    "error": " org.apache.spark.sql.catalyst.parser.ParseException: \nOperation not allowed: grant(line 1, pos 0)\n\n== SQL ==\ngrant SELECT, READ_METADATA, USAGE on DATABASE 'DB"
}


The above function is not working,

CodePudding user response:

Your question is not very clear, but I'll guess you're having problems in this part:

-d '{ "query": \"'"${content}"'\" } '

That will get you literal backslashes before the double quotes around your content, since backslashes inside single quotes are inserted literally. You could swap that for -d '{ "query": "'"${content}"'" }' or -d "{ \"query\": \"${content}\" }"

CodePudding user response:

Always use a tool that understands JSON when you need to build JSON. In this context, the widely-accepted tool is for the job is jq.

curl -X POST "${url}" \
  -H "Authorization: Bearer ${authtoken}" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg content "$content" '{"query": $content}')"
  • Related