create notebook programatically

Avinash_Narala
Databricks Partner

Hello,

I have json content of the notebook with me.

Can I know is there a way to create notebook with that content using python?

Hi Kaniz,

Thank you for your reply.

Actually I don't want to create dataframe. I have json content of notebook, which I got by reading a notebook itself, but I can't create a notebook from that json.
You can see below code to understand in detail what I want to do:

 

def export_notebook():
    export_payload = {
        "path": notebook_path,
        "format": "SOURCE"
    }
    response = requests.get(export_url, headers=headers, json=export_payload)
    response.raise_for_status()
    return response.json()["content"]
 
def import_notebook(new_content😞
    import_payload = {
        "path": new_notebook_path,
        "content": new_content
    }
    response = requests.post(import_url, headers=headers, json=import_payload)
    if response.status_code != 200:
        print(response.content)
    response.raise_for_status()
 
I can export my notebook and make changes to json, but can't import back to my workspace.
 
Please help me with this.

renancy
New Contributor III

hi @Avinash_Narala, just pinning this section because I'm on the search of the same procedure as you. Some important test i runned on the Topic is that, neither the magic command %sh or using the databricks CLI seens to work specifically with Notebooks, It will copy paste the result as a python file no matter what I do.
Hope there is an answer.
Tks!

 

Renancius

rtreves
Contributor

@Avinash_Narala @renancy Check out the databricks sdk documentation on `databricks.sdk.WorkspaceClient.workspace`: https://databricks-sdk-py.readthedocs.io/en/latest/workspace/workspace/workspace.html 

Something like the following may be helpful:

w.workspace.import_(
path="<path to file>",
format=workspace.ImportFormat.SOURCE,
content=base64.b64encode(f.read()).decode()
)