1

I want to import databricks notebook using workspace api import method. Content of notebook should be dynamic. I am trying using below code but it gives error:

malfunctioned request

request contains invalid json body. I have tried converting content to base64 encoded data and pass it in payload still it gives same error. main thing I want to achieve is , I want to generate content of notebook dynamically.

import requests
import os
import json

ctx = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
host_name = ctx['extraContext']['api_url']
host_token = ctx['extraContext']['api_token']
notebook_path = ctx['extraContext']['notebook_path']
new_path = os.path.join(os.path.dirname(notebook_path), 'New name')

data = {
  "content": "print(hellow world)",
  "path": new_path,
  "language": "PYTHON",
  "overwrite": true,
  "format": "SOURCE"
}

response = requests.post(
    '{host_name}/api/2.0/workspace/import',
    headers={'Authorization': f'Bearer {host_token}'},
    data = data
  ).json()
Alex Ott
  • 80,552
  • 8
  • 87
  • 132

1 Answers1

1

there are several problems here:

  • per documentation, the content field should be base64-encoded, so you need to do it as:
import base64
data = {
  "content": base64.b64encode("print(hellow world)".encode()),
  ...
}
  • the payload should be a JSON, but you're using data parameter that sends data as multipart form data (see docs). You need to use json parameter instead:
response = requests.post(
    f'{host_name}/api/2.0/workspace/import',
    headers={'Authorization': f'Bearer {host_token}'},
    json = data
  ).json()
  • You're trying to substitute host name, but you're using just string, not f-string, so you need to change '{host_name}/api/2.0/workspace/import' to f'{host_name}/api/2.0/workspace/import'
Alex Ott
  • 80,552
  • 8
  • 87
  • 132