Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: download notebooks as `ipynb` through UI (#8582)

Péter Gyarmati4e652e62eff4
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index 15dafcc0b1..e6b75998d5 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -59,6 +59,7 @@ export const MockRequestClient = {
getRunningNotebooks: vi.fn().mockResolvedValue({ files: [] }),
shutdownSession: vi.fn().mockResolvedValue({}),
exportAsHTML: vi.fn().mockResolvedValue({ html: "" }),
+ exportAsIPYNB: vi.fn().mockResolvedValue(""),
exportAsMarkdown: vi.fn().mockResolvedValue({ markdown: "" }),
exportAsPDF: vi.fn().mockResolvedValue(new Blob()),
autoExportAsHTML: vi.fn().mockResolvedValue({}),
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index dcdd413cb3..e307ef4ea6 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -31,6 +31,7 @@ import {
LayoutTemplateIcon,
LinkIcon,
MessagesSquareIcon,
+ NotebookIcon,
PanelLeftIcon,
PowerSquareIcon,
PresentationIcon,
@@ -123,8 +124,13 @@ export function useNotebookActions() {
const setCommandPaletteOpen = useSetAtom(commandPaletteAtom);
const setSettingsDialogOpen = useSetAtom(settingDialogAtom);
const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);
- const { exportAsMarkdown, readCode, saveCellConfig, updateCellOutputs } =
- useRequestClient();
+ const {
+ exportAsIPYNB,
+ exportAsMarkdown,
+ readCode,
+ saveCellConfig,
+ updateCellOutputs,
+ } = useRequestClient();
const takeScreenshots = useEnrichCellOutputs();
const hasDisabledCells = useAtomValue(hasDisabledCellsAtom);
@@ -199,6 +205,27 @@ export function useNotebookActions() {
setTimeout(() => window.dispatchEvent(afterprint), 0);
};
+ const handleDownloadAsIPYNB = async () => {
+ if (!filename) {
+ toastNotebookMustBeNamed();
+ return;
+ }
+
+ const runDownload = async (progress: ProgressState) => {
+ await updateCellOutputsWithScreenshots({
+ takeScreenshots: () => takeScreenshots({ progress }),
+ updateCellOutputs,
+ });
+ const ipynb = await exportAsIPYNB({ download: false });
+ downloadBlob(
+ new Blob([ipynb], { type: "application/x-ipynb+json" }),
+ Filenames.toIPYNB(document.title),
+ );
+ };
+
+ await withLoadingToast("Downloading IPYNB...", runDownload);
+ };
+
const actions: ActionButton[] = [
{
icon: <DownloadIcon size={14} strokeWidth={1.5} />,
@@ -240,6 +267,11 @@ export function useNotebookActions() {
);
},
},
+ {
+ icon: <NotebookIcon size={14} strokeWidth={1.5} />,
+ label: "Download as ipynb",
+ handle: handleDownloadAsIPYNB,
+ },
{
icon: <CodeIcon size={14} strokeWidth={1.5} />,
label: "Download Python code",
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 3bb1aaba72..7cb35d8845 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -181,6 +181,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
sendFileDetails = throwNotImplemented;
openTutorial = throwNotImplemented;
exportAsHTML = throwNotImplemented;
+ exportAsIPYNB = throwNotImplemented;
exportAsMarkdown = throwNotImplemented;
exportAsPDF = throwNotImplemented;
autoExportAsHTML = throwNotImplemented;
diff --git a/frontend/src/core/network/__tests__/requests-network.test.ts b/frontend/src/core/network/__tests__/requests-network.test.ts
index dcfd8aea37..37b0a13a72 100644
--- a/frontend/src/core/network/__tests__/requests-network.test.ts
+++ b/frontend/src/core/network/__tests__/requests-network.test.ts
@@ -113,5 +113,22 @@ describe("createNetworkRequests", () => {
}),
);
});
+
+ it("exportAsIPYNB should call the new endpoint as text", async () => {
+ const requests = createNetworkRequests();
+ await requests.exportAsIPYNB({
+ download: false,
+ } as any);
+
+ expect(mockClient.POST).toHaveBeenCalledWith(
+ "/api/export/ipynb",
+ expect.objectContaining({
+ body: expect.objectContaining({
+ download: false,
+ }),
+ parseAs: "text",
+ }),
+ );
+ });
});
});
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index 5d4b3d34c1..e017d00e53 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -49,6 +49,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
// Export operations start a connection
exportAsHTML: "startConnection",
+ exportAsIPYNB: "startConnection",
exportAsMarkdown: "startConnection",
exportAsPDF: "startConnection",
readCode: "startConnection",
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 86fed0daeb..b4bb0f3c60 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -381,6 +381,15 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponse);
},
+ exportAsIPYNB: async (request) => {
+ return getClient()
+ .POST("/api/export/ipynb", {
+ body: request,
+ parseAs: "text",
+ params: getParams(),
+ })
+ .then(handleResponse);
+ },
exportAsPDF: async (request) => {
return getClient()
.POST("/api/export/pdf", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 34844f4731..4de81be61a 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -75,6 +75,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
getRunningNotebooks: throwNotInEditMode,
shutdownSession: throwNotInEditMode,
exportAsHTML: throwNotInEditMode,
+ exportAsIPYNB: throwNotInEditMode,
exportAsMarkdown: throwNotInEditMode,
exportAsPDF: throwNotInEditMode,
autoExportAsHTML: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index ddaeb31b3a..cd74cf5978 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -60,6 +60,7 @@ export function createErrorToastingRequests(
getRunningNotebooks: "Failed to get running notebooks",
shutdownSession: "Failed to shutdown session",
exportAsHTML: "Failed to export HTML",
+ exportAsIPYNB: "Failed to export ipynb",
exportAsMarkdown: "Failed to export Markdown",
exportAsPDF: "Failed to export PDF",
autoExportAsHTML: "", // No toast
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index b0e5878e34..522e532f6d 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -180,6 +180,7 @@ export interface EditRequests {
) => Promise<RunningNotebooksResponse>;
// Export requests
exportAsHTML: (request: ExportAsHTMLRequest) => Promise<string>;
+ exportAsIPYNB: (request: ExportAsIPYNBRequest) => Promise<string>;
exportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<string>;
exportAsPDF: (request: ExportAsPDFRequest) => Promise<Blob>;
autoExportAsHTML: (request: ExportAsHTMLRequest) => Promise<null>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 0d2e5e6151..fef43c620f 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -587,6 +587,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
getWorkspaceFiles = throwNotImplemented;
getRunningNotebooks = throwNotImplemented;
shutdownSession = throwNotImplemented;
+ exportAsIPYNB = throwNotImplemented;
exportAsPDF = throwNotImplemented;
autoExportAsHTML = throwNotImplemented;
autoExportAsMarkdown = throwNotImplemented;
diff --git a/frontend/src/utils/__tests__/filenames.test.ts b/frontend/src/utils/__tests__/filenames.test.ts
index 3b6f340f0d..3724738c73 100644
--- a/frontend/src/utils/__tests__/filenames.test.ts
+++ b/frontend/src/utils/__tests__/filenames.test.ts
@@ -23,6 +23,12 @@ describe("Filenames", () => {
expect(Filenames.toPNG("test.foo.py")).toEqual("test.foo.png");
});
+ it("should convert filename to ipynb", () => {
+ expect(Filenames.toIPYNB("test")).toEqual("test.ipynb");
+ expect(Filenames.toIPYNB("test.txt")).toEqual("test.ipynb");
+ expect(Filenames.toIPYNB("test.foo.py")).toEqual("test.foo.ipynb");
+ });
+
it("should remove extension from filename", () => {
expect(Filenames.withoutExtension("test")).toEqual("test");
expect(Filenames.withoutExtension("test.txt")).toEqual("test");
@@ -39,6 +45,7 @@ describe("Filenames", () => {
expect(Filenames.toHTML(filename)).toEqual(`${withoutExt}.html`);
expect(Filenames.toPNG(filename)).toEqual(`${withoutExt}.png`);
expect(Filenames.toPY(filename)).toEqual(`${withoutExt}.py`);
+ expect(Filenames.toIPYNB(filename)).toEqual(`${withoutExt}.ipynb`);
// Ensure operations preserve unicode and special characters in base name
expect(withoutExt).not.toEqual("");
diff --git a/frontend/src/utils/filenames.ts b/frontend/src/utils/filenames.ts
index 48b96dd717..9f6d165f8e 100644
--- a/frontend/src/utils/filenames.ts
+++ b/frontend/src/utils/filenames.ts
@@ -15,6 +15,9 @@ export const Filenames = {
toPY: (filename: string): string => {
return Filenames.replace(filename, "py");
},
+ toIPYNB: (filename: string): string => {
+ return Filenames.replace(filename, "ipynb");
+ },
withoutExtension: (filename: string): string => {
// Just remove the last extension
const parts = filename.split(".");
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
index bca891ed48..0833f18352 100644
--- a/marimo/_server/api/endpoints/export.py
+++ b/marimo/_server/api/endpoints/export.py
@@ -27,6 +27,7 @@ from marimo._server.api.utils import parse_request
from marimo._server.export.exporter import AutoExporter, Exporter
from marimo._server.models.export import (
ExportAsHTMLRequest,
+ ExportAsIPYNBRequest,
ExportAsMarkdownRequest,
ExportAsPDFRequest,
ExportAsScriptRequest,
@@ -290,6 +291,65 @@ async def export_as_markdown(
)
+@requires("edit")
+async def export_as_ipynb(
+ *,
+ request: Request,
+) -> PlainTextResponse:
+ """
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ schema:
+ type: string
+ required: true
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ExportAsIPYNBRequest"
+ responses:
+ 200:
+ description: Export the notebook as IPYNB
+ content:
+ text/plain:
+ schema:
+ type: string
+ 400:
+ description: File must be saved before downloading
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=ExportAsIPYNBRequest)
+ session = app_state.require_current_session()
+
+ if not session.app_file_manager.is_notebook_named:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="File must have a name before exporting",
+ )
+
+ ipynb = Exporter().export_as_ipynb(
+ app=session.app_file_manager.app,
+ sort_mode="top-down",
+ session_view=session.session_view,
+ )
+
+ if body.download:
+ filename = get_download_filename(
+ session.app_file_manager.filename, "ipynb"
+ )
+ headers = make_download_headers(filename)
+ else:
+ headers = {}
+
+ # Download the IPYNB
+ return PlainTextResponse(
+ content=ipynb,
+ headers=headers,
+ )
+
+
@router.post("/auto_export/markdown")
@requires("edit")
async def auto_export_as_markdown(
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index bf6147a5a3..650dcbf626 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -5139,7 +5139,7 @@ components:
type: object
info:
title: marimo API
- version: 0.20.2
+ version: 0.20.4
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
@@ -5489,6 +5489,28 @@ paths:
description: Export the notebook as HTML
400:
description: File must be saved before downloading
+ /api/export/ipynb:
+ post:
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ExportAsIPYNBRequest'
+ responses:
+ 200:
+ content:
+ text/plain:
+ schema:
+ type: string
+ description: Export the notebook as IPYNB
+ 400:
+ description: File must be saved before downloading
/api/export/markdown:
post:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index e2bc525916..42fdc30d37 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -756,6 +756,54 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/export/ipynb": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header: {
+ "Marimo-Session-Id": string;
+ };
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["ExportAsIPYNBRequest"];
+ };
+ };
+ responses: {
+ /** @description Export the notebook as IPYNB */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "text/plain": string;
+ };
+ };
+ /** @description File must be saved before downloading */
+ 400: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/export/markdown": {
parameters: {
query?: never;
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index fe92719fdf..0b5fffb964 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import json
import os
import re
import shutil
@@ -212,6 +213,24 @@ def test_export_markdown(client: TestClient) -> None:
)
+ not DependencyManager.nbformat.has(), reason="nbformat not installed"
+)
+@with_session(SESSION_ID)
+def test_export_ipynb(client: TestClient) -> None:
+ response = client.post(
+ "/api/export/ipynb",
+ headers=HEADERS,
+ json={
+ "download": False,
+ },
+ )
+ assert response.status_code == 200
+ ipynb_json = json.loads(response.text)
+ assert "cells" in ipynb_json
+ assert ipynb_json["nbformat"] == 4
+
+
@with_read_session(SESSION_ID)
def test_other_exports_dont_work_in_read(client: TestClient) -> None:
response = client.post(
@@ -230,6 +249,14 @@ def test_other_exports_dont_work_in_read(client: TestClient) -> None:
},
)
assert response.status_code == 401
+ response = client.post(
+ "/api/export/ipynb",
+ headers=HEADERS,
+ json={
+ "download": False,
+ },
+ )
+ assert response.status_code == 401
@with_session(SESSION_ID)
@@ -623,6 +650,30 @@ def test_export_script_download_edge_case_filenames(
assert "attachment" in response.headers["Content-Disposition"]
+ not DependencyManager.nbformat.has(), reason="nbformat not installed"
+)
+@with_session(SESSION_ID)
+def test_export_ipynb_download_edge_case_filenames(
+ client: TestClient,
+) -> None:
+ """Test that ipynb export with download=True works for non-ASCII filenames."""
+ for filename in EDGE_CASE_FILENAMES:
+ session = get_session_manager(client).get_session(SESSION_ID)
+ assert session
+ session.app_file_manager.filename = filename
+ response = client.post(
+ "/api/export/ipynb",
+ headers=HEADERS,
+ json={
+ "download": True,
+ },
+ )
+ assert response.status_code == 200, f"Failed for filename: {filename}"
+ assert "Content-Disposition" in response.headers
+ assert "attachment" in response.headers["Content-Disposition"]
+
+
@with_session(SESSION_ID)
def test_update_cell_outputs_new_cell(client: TestClient) -> None:
"""Test updating cell outputs for a cell with no existing output."""