cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Community Platform Discussions
Connect with fellow community members to discuss general topics related to the Databricks platform, industry trends, and best practices. Share experiences, ask questions, and foster collaboration within the community.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

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.
 
1 REPLY 1

Kaniz_Fatma
Community Manager
Community Manager

Hi @Mehdi-LAMRANI

  • Ensure that your JavaScript code is being executed from a domain that is allowed to make requests to the Databricks API. If the JavaScript code is running in a different domain (e.g., a local file), you might encounter CORS issues. You can check the browser console for any CORS-related errors.
  • Confirm that your JavaScript environment has network connectivity to the Databricks API endpoint. Sometimes, network restrictions or firewalls can prevent requests from being made.
  • Verify that the token variable contains the correct Databricks API token. Make sure itโ€™s not expired and has the necessary permissions to execute SQL statements.
  • Ensure that the URL components (such as baseUrlwarehouseIdcatalogschema, and statement) are properly URL-encoded. Special characters or spaces in these values could cause issues.
  • Add some additional logging to your JavaScript code to see if you can capture more information about the error. For example, log the URL being used for the request and any response received.

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group