SQL Statement Execution API w/ Javascript (REST)

Mehdi-LAMRANI
New Contributor II

I need to use Databricks SQL Statement Execution API w/ Javascript (see example post )

For some reason, Curl Works, Python works, but Javascript fails.

This works : 
(curl)
______________________________

curl --request POST \
https://adb-5750xxxxxxx.azuredatabricks.net/api/2.0/sql/statements/ \
--header "Authorization: Bearer dapi5c3xxxxxxx" \
--header "Content-Type: application/json" \
--data '{
"warehouse_id": "368axxxxxxx",
"catalog": "main",
"schema": "myschema",
"statement": "SELECT * FROM mytable LIMIT 1"
}'


This works : 
(python)
____________________________

import os
import requests
import json

 
# set databricks host
host = "https://"+DATABRICKS_HOST+"/api/2.0/sql/statements"

# sql query
warehouse_id = DATABRICKS_WAREHOUSE_ID
query = "SELECT * from mytable limit 1"

query_resp = requests.post(url=host, headers={"Authorization": "Bearer " + DATABRICKS_API_TOKEN}, data=json.dumps({"statement": query, "warehouse_id": warehouse_id, "catalog": "main","schema": "myschema"}))

print(query_resp.status_code)
print(query_resp.json())

This does NOT work : 
(javascript)
______________________________

displayHTML(f"""
<!DOCTYPE html>
<html>
<body>

<h3>Log</h3>
<textarea id="log" rows="10" cols="200" readonly></textarea>

<script>

const warehouseId = "368xxxxx";
const token = "dapixxxxxx";
const catalog = "main";
const schema = "ocealia";
const statement = "SELECT * FROM cereales LIMIT 1";

const fetchData = async () => {{
const url = `${{baseUrl}}`;
const data = {{
warehouse_id: warehouseId,
catalog: catalog,
schema: schema,
statement: statement,
}};

const options = {{
method: "POST",
headers: {{
Authorization: `Bearer ${{token}}`,
"Content-Type": "application/json",
}},
body: JSON.stringify(data),
}};

try {{
const response = await fetch(url, options);
if (!response.ok) {{
throw new Error(`Error fetching data: ${{response.status}}`);
}}
const jsonData = await response.json();
logMessage("Results:", jsonData);
}} catch (error) {{
logMessage( error);
}}
}};
 
function logMessage(message) {{
var logArea = document.getElementById('log');
logArea.value += message + "\\n";
logArea.scrollTop = logArea.scrollHeight; // Scroll to the bottom
}}

fetchData();
</script>

</body>
</html>
""")
 
____________________________
For some obscure reason it throws : 
TypeError: Failed to fetch
 
It is interesting to note that when calling the clusters list GET request, it DOES succeed.
let url = `https://${{DATABRICKS_HOST}}/api/2.0/clusters/list`
For some reason this one works but the POST sql statement fails
 
Any help is truly appreciated.