### Get Sample Orders Response Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Example JSON response for the Get Sample Orders endpoint, providing a list of sample order keys. ```json { "sample_order_keys": [1, 32, 33, 34, 35] } ``` -------------------------------- ### Get Sample Orders cURL Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Example of how to retrieve a sample of order keys using cURL. This is helpful for testing and development environments. ```bash curl -X GET "http://localhost:8000/api/v1/orders/sample" ``` -------------------------------- ### Install App Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/blog/2025-03-17-dabs/2025-03-17-dabs.mdx Set up a Python virtual environment and install the application's dependencies using pip. ```bash python3 -m venv .venv source .venv/bin/activate pip install -r src/app/requirements.txt ``` -------------------------------- ### Install Dependencies and Run FastAPI App Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/README.md Set up a virtual environment, install project dependencies, configure environment variables, and run the FastAPI application locally using uvicorn. ```bash # Create and activate virtual environment python -m venv venv source venv/bin/activate # Install dependencies within active venv pip install -r requirements.txt # Set environment variables (if not using .env file) export DATABRICKS_WAREHOUSE_ID=your-warehouse-id # If using a .env file: cp .env.example .env # Fill in .env fields # Run the application uvicorn app:app --reload ``` -------------------------------- ### Project Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/authentication/users_obo.mdx List of Python packages required for the Databricks Apps OBO authentication example. Install these using pip. ```python databricks-sdk databricks-sql-connector streamlit ``` -------------------------------- ### Install Dependencies for FastAPI Video Streaming Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/volumes_stream_video.mdx Install the required Python packages for building a FastAPI application that streams video. Ensure these are listed in your requirements.txt file. ```python fastapi requests uvicorn ``` -------------------------------- ### Python Databricks Connect Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/dash/compute/compute_connect.mdx Connect to a Databricks cluster using Databricks Connect and execute SQL queries. Ensure the DATABRICKS_HOST environment variable is set. This example performs an inner join and generates a sequence. ```python import os from databricks.connect import DatabricksSession cluster_id = "0709-132523-cnhxf2p6" spark = DatabricksSession.builder.remote( host=os.getenv("DATABRICKS_HOST"), cluster_id=cluster_id ).getOrCreate() # SQL operations example a = "(VALUES (1, 'A1'), (2, 'A2'), (3, 'A3')) AS a(id, value)" b = "(VALUES (2, 'B1'), (3, 'B2'), (4, 'B3')) AS b(id, value)" # Inner join example query = f"SELECT a.id, a.value AS value_a, b.value AS value_b FROM {a} INNER JOIN {b} ON a.id = b.id" result = spark.sql(query).toPandas() print(result) # Generate sequence result = spark.range(10).toPandas() print(result) ``` -------------------------------- ### Uvicorn Server Output - Initial Startup Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/create.mdx Example output from the Uvicorn server during initial startup, showing the directories being watched for changes and the address the server is running on. ```bash INFO: Will watch for changes in these directories: ['/Users/user.name/home/databricks-apps-cookbook/fastapi'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [56162] using StatReload INFO: Started server process [56164] INFO: Waiting for application startup. INFO: Application startup complete. ``` -------------------------------- ### Running the Lakebase Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/README.md Steps to deploy and validate Lakebase resources, including creating resources, testing endpoints, and cleaning up to avoid costs. ```APIDOC ## Running the Lakebase Example ### 1. Create Lakebase Resources With the app running and your `.env` file configured: 1. Navigate to http://localhost:8000/docs (Swagger UI) 2. Find the `/api/v1/resources/create-lakebase-resources` endpoint 3. Click **Try it out** 4. Set `create_resources` to `true` (confirming you understand the costs) 5. Configure other fields as needed 6. Click **Execute** 7. Wait for resource creation (takes several minutes) ### 2. Validate and Test Once resources are created: 1. Check the Databricks UI for: database instance, database, catalog, and `orders_synced` table 2. Restart your local app: `uvicorn app:app --reload` 3. Return to http://localhost:8000/docs - you should now see the `/orders` endpoints available ### 3. Clean Up Resources To avoid ongoing costs: 1. Navigate to `/api/v1/resources/delete-lakebase-resources` endpoint 2. Set `confirm_deletion` to `true` 3. Click **Execute** ``` -------------------------------- ### Get Sample Order Keys Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/APP_DESCRIPTION.md Returns the first 5 order keys for testing and discovery purposes. ```APIDOC ## GET /api/v1/orders/sample ### Description Returns the first 5 order keys for testing and discovery. ### Method GET ### Endpoint /api/v1/orders/sample ### Response #### Success Response (200) - `{ "sample_order_keys": [1, 2, 3, 4, 5] }` ``` -------------------------------- ### Install Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/mcp_connect.mdx Install the necessary Python packages for Databricks SDK, FastAPI, uvicorn, and MCP CLI. ```python databricks-sdk fastapi uvicorn mcp[cli] ``` -------------------------------- ### Get Sample Order Keys Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/APP_DESCRIPTION.md Retrieves sample order keys. ```APIDOC ## GET /api/v1/orders/sample ### Description Retrieves sample order keys. ### Method GET ### Endpoint /api/v1/orders/sample ``` -------------------------------- ### Install Python Packages Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/deploy.md Install all required Python packages for the project using the pip package manager. Ensure your virtual environment is activated before running this command. ```bash pip install -r requirements.txt ``` -------------------------------- ### Create Lakebase Resources with cURL Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_resources_create.mdx Use cURL to send POST requests to create Lakebase resources. The first example creates resources with default settings. The second example specifies custom capacity, node count, and enables readable secondaries. ```bash curl -X POST "http://localhost:8000/api/v1/resources/create-lakebase-resources?create_resources=true" ``` ```bash curl -X POST "http://localhost:8000/api/v1/resources/create-lakebase-resources?create_resources=true&capacity=CU_2&node_count=2&enable_readable_secondaries=true" ``` -------------------------------- ### Run Reflex App Locally Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/deploy.md Run the Reflex application locally. Make sure your virtual environment is activated and dependencies are installed. ```bash reflex run app.py ``` -------------------------------- ### Get Sample Order Keys from Lakebase Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt Fetches a specified number of order keys from the Lakebase table, useful for testing other order-related endpoints. Ensure DATABRICKS_TOKEN is set. ```bash curl -s "http://localhost:8000/api/v1/orders/sample" \ -H "Authorization: Bearer $DATABRICKS_TOKEN" ``` -------------------------------- ### Project Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/aiml/mcp_connect.mdx Lists the necessary Python packages for this project, including `databricks-sdk`, `streamlit`, and `mcp[cli]`. These should be installed in your environment. ```python databricks-sdk streamlit mcp[cli] ``` -------------------------------- ### Run Databricks App in Development Environment Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/blog/2025-03-17-dabs/2025-03-17-dabs.mdx Starts the Databricks application resource and initiates the first code deployment after deployment. Use this to verify your application is running correctly. ```bash databricks bundle run hello-world-app -t dev ``` -------------------------------- ### Get 5 Sample Order Keys Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt Fetches 5 sample order keys from the Lakebase table. This is useful for testing other order-related endpoints. ```APIDOC ## GET /api/v1/orders/sample ### Description Returns 5 sample order keys from the Lakebase table. ### Method GET ### Endpoint /api/v1/orders/sample ### Response #### Success Response (200) - **sample_order_keys** (array) - An array of sample order keys. #### Response Example ```json {"sample_order_keys": [1, 32, 64, 128, 256]} ``` ``` -------------------------------- ### Project Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/visualizations/visualizations_map.mdx Lists the Python packages required for the Databricks Apps cookbook examples, including Streamlit, Streamlit Folium, Databricks SDK, and Databricks SQL Connector. ```python streamlit streamlit-folium databricks-sdk databricks-sql-connector ``` -------------------------------- ### Get Sample Orders Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Retrieves a sample of 5 random order keys from the database. Useful for quick data inspection or testing. Handles potential errors during the database query. ```python # 2. GET SAMPLE ORDERS @router.get("/sample", response_model=OrderSample, summary="Get 5 random order keys") async def get_sample_orders(db: AsyncSession = Depends(get_async_db)): try: stmt = select(Order.o_orderkey).limit(5) result = await db.execute(stmt) order_keys = result.scalars().all() return OrderSample(sample_order_keys=order_keys) except Exception as e: logger.error(f"Error getting sample orders: {e}") raise HTTPException(status_code=500, detail="Failed to retrieve sample orders") ``` -------------------------------- ### Get Orders Count Response Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Example JSON response for the Get Orders Count endpoint, showing the total number of orders. ```json { "total_orders": 1500000 } ``` -------------------------------- ### Get Orders Count cURL Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Example of how to retrieve the total count of orders using cURL. This is useful for monitoring and dashboarding purposes. ```bash curl -X GET "http://localhost:8000/api/v1/orders/count" ``` -------------------------------- ### On-Behalf-Of User Authentication Example Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/reflex/APP_DESCRIPTION.md Demonstrates running queries as the logged-in user versus the app's service principal. Populates dropdowns for warehouse, catalog, schema, and table selection. ```python from databricks.sdk.runtime import * def run_query_obo(warehouse_id, catalog_name, schema_name, table_name, auth_mode): # auth_mode can be 'obo' or 'sp' query = f"SELECT * FROM {catalog_name}.{schema_name}.{table_name} LIMIT 100" results = sql.execute_query(query, warehouse_id=warehouse_id, auth_mode=auth_mode) return results # Example usage: # print(run_query_obo("my_warehouse_id", "main", "default", "my_table", "obo")) ``` -------------------------------- ### Set Up Python Virtual Environment Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/deploy.md Create and activate a Python virtual environment for the Reflex framework. It is recommended to use separate environments for each framework. ```bash cd reflex python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Install Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/test.mdx List of Python dependencies required for the FastAPI application and its testing setup, including FastAPI, Pytest, Pytest-cov, and Uvicorn. ```python fastapi pytest pytest-cov uvicorn ``` -------------------------------- ### Streamlit App to Get Workflow Results Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/workflows/workflows_get_results.mdx Use this Streamlit app to input a task run ID and display its results. Ensure the Databricks SDK and Streamlit are installed. ```python import streamlit as st from databricks.sdk import WorkspaceClient w = WorkspaceClient() task_run_id = st.text_input( label="Specify a task run ID", placeholder="293894477334278", ) results = w.jobs.get_run_output(task_run_id) st.text(results) ``` -------------------------------- ### Get Orders with Cursor-Based Pagination Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Retrieves orders using cursor-based pagination. It fetches a specified number of records starting after a given cursor, suitable for infinite scrolling or large datasets. Ensure the `Order` model and database session are correctly configured. ```python from fastapi import APIRouter, Query, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.database import get_async_db from app.models.order import Order from app.schemas.order import OrderListCursorResponse, CursorPaginationInfo, OrderRead, OrderStatusUpdate, OrderStatusUpdateResponse from loguru import logger router = APIRouter() @router.get("/stream", response_model=OrderListCursorResponse, summary="Get orders with cursor-based pagination") async def get_orders_by_cursor( cursor: int = Query(0, ge=0, description="Start after this order key (0 for beginning)"), page_size: int = Query(100, ge=1, le=1000, description="Number of records to fetch (max 1000)"), db: AsyncSession = Depends(get_async_db), ): try: stmt = ( select(Order) .where(Order.o_orderkey > cursor) .order_by(Order.o_orderkey) .limit(page_size + 1) ) result = await db.execute(stmt) all_orders = result.scalars().all() has_next = len(all_orders) > page_size orders = all_orders[:page_size] has_previous = cursor > 0 next_cursor = orders[-1].o_orderkey if orders and has_next else None previous_cursor = max(0, cursor - page_size) if has_previous else None pagination_info = CursorPaginationInfo( page_size=page_size, has_next=has_next, has_previous=has_previous, next_cursor=next_cursor, previous_cursor=previous_cursor, ) return OrderListCursorResponse(orders=orders, pagination=pagination_info) except Exception as e: logger.error(f"Error getting cursor-based orders: {e}") raise HTTPException(status_code=500, detail="Failed to retrieve orders") ``` -------------------------------- ### FastAPI Application Startup with Lifespan Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/lakebase_connection.mdx Configure application startup and shutdown events to initialize the Lakebase connection and manage token refresh. ```python from contextlib import asynccontextmanager from fastapi import FastAPI from config.database import init_engine, start_token_refresh, stop_token_refresh, check_database_exists @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan management""" # Startup if check_database_exists(): init_engine() await start_token_refresh() logger.info("Application started with Lakebase connection") else: logger.warning("Lakebase database not found - orders endpoints disabled") yield # Shutdown await stop_token_refresh() logger.info("Application shutdown complete") app = FastAPI(lifespan=lifespan) ``` -------------------------------- ### Initialize MCP Session and List Tools (OAuth) Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/aiml/mcp_connect.mdx This snippet initializes an MCP session using an OAuth token and then lists available tools. It requires the `databricks-sdk` and `streamlit` libraries. Ensure the `github_u2m_connection` is configured in Unity Catalog. ```python import streamlit as st from databricks.sdk import WorkspaceClient from databricks.sdk.service.serving import ExternalFunctionRequestHttpMethod import json token = st.context.headers.get("x-forwarded-access-token") w = WorkspaceClient(token=token, auth_type="pat") def init_mcp_session(w: WorkspaceClient, connection_name: str): init_payload = { "jsonrpc": "2.0", "id": "init-1", "method": "initialize", "params": {} } response = w.serving_endpoints.http_request( conn=connection_name, method=ExternalFunctionRequestHttpMethod.POST, path="/", json=init_payload, ) return response.headers.get("mcp-session-id") connection_name = "github_u2m_connection" http_method = ExternalFunctionRequestHttpMethod.POST path = "/" headers = {"Content-Type": "application/json"} payload = {"jsonrpc": "2.0", "id": "list-1", "method": "tools/list"} if st.button("Run"): session_id = init_mcp_session(w, connection_name) headers["Mcp-Session-Id"] = session_id response = w.serving_endpoints.http_request( conn=connection_name, method=http_method, path=path, headers=headers, json=payload, ) st.json(response.json()) ``` -------------------------------- ### Clone and Run Databricks Apps Cookbook Locally Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt Steps to clone the repository, authenticate with Databricks, and run the Streamlit, Dash, Reflex, and FastAPI applications locally. ```bash # Clone the repository git clone https://github.com/databricks-solutions/databricks-apps-cookbook.git cd databricks-apps-cookbook # Authenticate with your workspace (OAuth U2M) databricks auth login --host https://my-workspace.cloud.databricks.com/ # --- Streamlit --- cd streamlit python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt export DATABRICKS_HOST=https://my-workspace.cloud.databricks.com/ streamlit run app.py # --- Dash --- cd dash python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt python app.py # --- Reflex --- cd reflex python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt reflex run app.py # --- FastAPI --- cd fastapi python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt cp .env.example .env # fill in DATABRICKS_WAREHOUSE_ID, etc. uvicorn app:app --reload # OpenAPI docs available at http://localhost:8000/docs ``` -------------------------------- ### Get Total Order Count (Lakebase) Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt Retrieves the total number of rows in the Lakebase `orders_synced` table. This endpoint is useful for getting a quick count of all orders. ```APIDOC ## GET /api/v1/orders/count ### Description Returns the total number of rows in the Lakebase `orders_synced` table. ### Method GET ### Endpoint /api/v1/orders/count ### Response #### Success Response (200) - **total_orders** (integer) - The total count of orders. #### Response Example ```json {"total_orders": 1500000} ``` ``` -------------------------------- ### Main FastAPI Application Entrypoint Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/create.mdx This is the main file for your FastAPI application. It initializes the FastAPI instance and includes the main API router. Ensure the title, description, and version are set appropriately for your application. ```python from fastapi import FastAPI from routes import api_router app = FastAPI( title="FastAPI & Databricks Apps", description="A simple FastAPI application example for Databricks Apps runtime", version="1.0.0", ) # Router assignment app.include_router(api_router) ``` -------------------------------- ### MCP Server Setup with FastAPI Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/mcp_connect.mdx This code sets up a FastAPI application to serve an MCP server. It defines endpoints for listing and calling tools, integrates with the MCP session manager, and includes middleware to capture request headers. It also serves a static index.html file for the root path. ```python @mcp._mcp_server.list_tools() async def list_tools(): tools_dict = list_github_tools() return tools_dict.get("result", {}).get("tools", []) @mcp._mcp_server.call_tool() async def call_tool(name: str, arguments: dict): response = call_github_tool(name, arguments) return response.get("result", {}).get("content", []) mcp_app = mcp.streamable_http_app() app = FastAPI( lifespan=lambda _: mcp.session_manager.run(), ) @app.middleware("http") async def capture_headers(request: Request, call_next): header_store.set(dict(request.headers)) return await call_next(request) @app.get("/", include_in_schema=False) async def serve_index(): return FileResponse(STATIC_DIR / "index.html") app.mount("/", mcp_app) ``` -------------------------------- ### Make HTTP Requests with On-Behalf-Of-User (OBO) Auth Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt For OBO authentication, retrieve the user token from the request headers and initialize `WorkspaceClient` with it. This example shows initializing an MCP session and listing tools. ```python # --- On-behalf-of-user (OBO) – requires App configured with OBO auth --- user_token = st.context.headers.get("x-forwarded-access-token") w_obo = WorkspaceClient(token=user_token, auth_type="pat") # MCP protocol example: initialise a session and list tools init_response = w_obo.serving_endpoints.http_request( conn="github_u2m_connection", method=ExternalFunctionRequestHttpMethod.POST, path="/", json={"jsonrpc": "2.0", "id": "init-1", "method": "initialize", "params": {}}, ) session_id = init_response.headers.get("mcp-session-id") tools_response = w_obo.serving_endpoints.http_request( conn="github_u2m_connection", method=ExternalFunctionRequestHttpMethod.POST, path="/", headers={"Mcp-Session-Id": session_id, "Content-Type": "application/json"}, json={"jsonrpc": "2.0", "id": "list-1", "method": "tools/list"}, ) st.json(tools_response.json()) ``` -------------------------------- ### Start Background Token Refresh Task Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/lakebase_connection.mdx Starts the background task responsible for refreshing database credentials. If the task is not already running or has completed, this function creates a new asyncio task to execute the `refresh_token_background` coroutine. ```python async def start_token_refresh(): """Start the background token refresh task""" global token_refresh_task if token_refresh_task is None or token_refresh_task.done(): token_refresh_task = asyncio.create_task(refresh_token_background()) logger.info("Background token refresh task started") ``` -------------------------------- ### Get Order Count Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/APP_DESCRIPTION.md Retrieves the total count of orders. ```APIDOC ## GET /api/v1/orders/count ### Description Retrieves the total count of orders. ### Method GET ### Endpoint /api/v1/orders/count ``` -------------------------------- ### Clone and Navigate Repository Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/deploy.md Clone the databricks-apps-cookbook repository and navigate into the project directory. This is the initial step for both local and Databricks deployment workflows. ```bash git clone https://github.com/databricks-solutions/databricks-apps-cookbook.git cd databricks-apps-cookbook ``` -------------------------------- ### Get Order Count Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/APP_DESCRIPTION.md Returns the total number of orders in the Lakebase database. ```APIDOC ## GET /api/v1/orders/count ### Description Returns the total number of orders in the Lakebase database. ### Method GET ### Endpoint /api/v1/orders/count ### Response #### Success Response (200) - `{ "total_orders": }` ``` -------------------------------- ### Project Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/dash/authentication/users_get_current.mdx Lists the necessary Python packages for the Databricks App. Ensure these are installed in your environment. ```yaml dash ``` -------------------------------- ### Get Sample Orders Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Retrieves a sample of 5 random order keys from the Lakebase table. ```APIDOC ## GET /sample ### Description Get a sample of 5 random order keys. ### Method GET ### Endpoint /sample ### Parameters None ### Request Example None ### Response #### Success Response (200) - **sample_order_keys** (array of integers) - A list of 5 random order keys. #### Response Example ```json { "sample_order_keys": [ 1001, 2005, 3010, 4002, 5008 ] } ``` ``` -------------------------------- ### Create Lakebase Resources using curl Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt Provisions a Databricks Lakebase PostgreSQL database instance, a Unity Catalog foreign catalog, and a synced DLT pipeline. Ensure `create_resources=true` is passed to confirm, as this incurs costs. ```bash curl -s -X POST -G "http://localhost:8000/api/v1/resources/create-lakebase-resources" \ --data-urlencode "create_resources=true" \ --data-urlencode "capacity=CU_1" \ --data-urlencode "node_count=1" \ --data-urlencode "enable_readable_secondaries=false" \ --data-urlencode "retention_window_in_days=7" \ -H "Authorization: Bearer $DATABRICKS_TOKEN" ``` -------------------------------- ### Get Total Order Count Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Retrieves the total number of orders available in the Lakebase table. ```APIDOC ## GET /count ### Description Get the total count of orders. ### Method GET ### Endpoint /count ### Parameters None ### Request Example None ### Response #### Success Response (200) - **total_orders** (integer) - The total number of orders. #### Response Example ```json { "total_orders": 1500 } ``` ``` -------------------------------- ### Clone Databricks Apps Cookbook Repository Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/blog/2025-03-17-dabs/2025-03-17-dabs.mdx Clone the sample GitHub repository to your local machine to begin development. ```bash git clone https://github.com/pbv0/databricks-apps-dabs cd databricks-apps-dabs ``` -------------------------------- ### Project Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/lakebase_connection.mdx List the necessary Python packages for connecting to Lakebase. Ensure these versions are installed in your environment. ```python databricks-sdk>=0.60.0 sqlalchemy asyncpg python-dotenv ``` -------------------------------- ### Get Single Order Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/APP_DESCRIPTION.md Retrieves a single order by its primary key. Used for order detail views. ```APIDOC ## GET /api/v1/orders/{order_key} ### Description Retrieves a single order by its primary key. ### Method GET ### Endpoint /api/v1/orders/{order_key} #### Path Parameters - **order_key** (integer) - Integer order key (must be > 0) ### Response #### Success Response (200) Full order object with fields: order key, customer key, order status, total price, order date, order priority, clerk, ship priority, and comment. #### Error Responses - 400 if order key is invalid (≤ 0) - 404 if order not found ``` -------------------------------- ### List GitHub Tools via MCP Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/mcp_connect.mdx This function lists the available tools on the GitHub MCP server. It first calls `init_github_tools` to establish a session and then makes an HTTP request to the MCP server with the 'tools/list' method, including the MCP Session ID in the headers. The response containing the list of tools is returned. ```python def list_github_tools() -> Dict[str, Any]: session_id = init_github_tools() headers = header_store.get({}) token=headers["x-forwarded-access-token"] json = { "jsonrpc": "2.0", "id": "list-1", "method": "tools/list", } try: response = WorkspaceClient(token=token, auth_type="pat").serving_endpoints.http_request( conn="github_u2m_connection", method=ExternalFunctionRequestHttpMethod.POST, path="/", json=json, headers={ "Mcp-Session-Id": session_id } ) except Exception as e: print(f"Error: {e}") return {"error": str(e)} print(f"Response list tools: {response.json()}") return response.json() ``` -------------------------------- ### OAuth User to Machine Per User (On-behalf-of-user) Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/dash/aiml/mcp_connect.mdx Initializes an MCP session and lists available tools using an OAuth token for authentication. Requires the `databricks-sdk` and Flask. ```python from databricks.sdk import WorkspaceClient from databricks.sdk.service.serving import ExternalFunctionRequestHttpMethod import json from flask import request token = request.headers.get("x-forwarded-access-token") w = WorkspaceClient(token=token, auth_type="pat") def init_mcp_session(w: WorkspaceClient, connection_name: str): init_payload = { "jsonrpc": "2.0", "id": "init-1", "method": "initialize", "params": {} } response = w.serving_endpoints.http_request( conn=connection_name, method=ExternalFunctionRequestHttpMethod.POST, path="/", json=init_payload, ) return response.headers.get("mcp-session-id") connection_name = "github_u2m_connection" http_method = ExternalFunctionRequestHttpMethod.POST path = "/" headers = {"Content-Type": "application/json"} payload = {"jsonrpc": "2.0", "id": "list-1", "method": "tools/list"} session_id = init_mcp_session(w, connection_name) headers["Mcp-Session-Id"] = session_id response = w.serving_endpoints.http_request( conn=connection_name, method=http_method, path=path, headers=headers, json=payload, ) print(response.json()) ``` -------------------------------- ### Order Status Update Response Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Example JSON response after successfully updating an order's status. ```json { "o_orderkey": 1, "o_orderstatus": "F", "message": "Order status updated successfully" } ``` -------------------------------- ### Root Endpoint Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/fastapi/APP_DESCRIPTION.md Returns a welcome message with basic app information and a link to the API docs. ```APIDOC ## GET / ### Description Returns a welcome message with basic app information and a link to the API docs. ### Method GET ### Endpoint / ### Response #### Success Response (200) - App name (string) - Welcome message (string) - Link to `/docs` (string) ``` -------------------------------- ### Get Orders by Page Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Retrieves orders using page-based pagination, allowing users to fetch data in chunks. ```APIDOC ## GET /pages ### Description Get orders with page-based pagination. ### Method GET ### Endpoint /pages ### Parameters #### Query Parameters - **page** (integer) - Required - Page number (1-based). - **page_size** (integer) - Optional - Number of records per page (max 1000). Defaults to 100. - **include_count** (boolean) - Optional - Include total count for pagination info. Defaults to True. ### Request Example None ### Response #### Success Response (200) - **orders** (array of Order objects) - A list of orders for the current page. - **pagination** (PaginationInfo object) - Information about the pagination. - **page** (integer) - The current page number. - **page_size** (integer) - The number of records per page. - **total_pages** (integer) - The total number of pages. - **total_count** (integer) - The total number of orders. - **has_next** (boolean) - Indicates if there is a next page. - **has_previous** (boolean) - Indicates if there is a previous page. #### Response Example ```json { "orders": [ { "o_orderkey": 1001, "o_custkey": 123, "o_orderstatus": "O", "o_totalprice": 1000.50, "o_orderdate": "2023-01-15T00:00:00", "o_orderpriority": "HIGH", "o_clerk": "John Doe", "o_shippriority": 0, "o_comment": "Some comment" } ], "pagination": { "page": 1, "page_size": 100, "total_pages": 15, "total_count": 1500, "has_next": true, "has_previous": false } } ``` ``` -------------------------------- ### Order Pagination Response Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Example JSON response for paginated orders, including order details and pagination metadata. ```json { "orders": [ { "o_orderkey": 1, "o_custkey": 370, "o_orderstatus": "O", "o_totalprice": 172799.49, "o_orderdate": "1996-01-02", "o_orderpriority": "5-LOW", "o_clerk": "Clerk#000000951", "o_shippriority": 0, "o_comment": "nstructions sleep furiously among" }, { "o_orderkey": 2, "o_custkey": 781, "o_orderstatus": "O", "o_totalprice": 46929.18, "o_orderdate": "1996-12-01", "o_orderpriority": "1-URGENT", "o_clerk": "Clerk#000000880", "o_shippriority": 0, "o_comment": "foxes. pending accounts at the pending" } ], "pagination": { "page": 1, "page_size": 2, "total_pages": 750000, "total_count": 1500000, "has_next": true, "has_previous": false } } ``` -------------------------------- ### Download and serve file from Unity Catalog Volume Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/volumes/volumes_download.mdx This Python script uses Streamlit and the Databricks SDK to allow users to input a file path from a Unity Catalog volume, download the file's content, and then offer it as a download button. Ensure the app's service principal has the necessary Unity Catalog permissions. ```python import os import streamlit as st from databricks.sdk import WorkspaceClient w = WorkspaceClient() download_file_path = st.text_input( label="Path to file", placeholder="/Volumes/catalog/schema/volume_name/file.csv" ) response = w.files.download(download_file_path) file_data = response.contents.read() file_name = os.path.basename(download_file_path) st.download_button(label="Download", data=file_data, file_name=file_name) ``` -------------------------------- ### Create Lakebase Resources Source: https://context7.com/databricks-solutions/databricks-apps-cookbook/llms.txt Provisions a Databricks Lakebase PostgreSQL database instance, a Unity Catalog foreign catalog, and a synced DLT pipeline. Warning: this incurs real costs; pass `create_resources=true` to confirm. ```APIDOC ## POST /api/v1/resources/create-lakebase-resources ### Description Provisions a Databricks Lakebase PostgreSQL database instance, a Unity Catalog foreign catalog, and a synced DLT pipeline from `samples.tpch.orders`. Warning: this incurs real costs; pass `create_resources=true` to confirm. ### Method POST ### Endpoint /api/v1/resources/create-lakebase-resources ### Parameters #### Query Parameters - **create_resources** (boolean) - Required - Pass `true` to confirm resource creation. - **capacity** (string) - Optional - Specifies the capacity for the instance (e.g., `CU_1`). - **node_count** (integer) - Optional - Specifies the number of nodes. - **enable_readable_secondaries** (boolean) - Optional - Enables readable secondaries. - **retention_window_in_days** (integer) - Optional - Sets the retention window in days. ### Request Example ```bash curl -s -X POST -G "http://localhost:8000/api/v1/resources/create-lakebase-resources" \ --data-urlencode "create_resources=true" \ --data-urlencode "capacity=CU_1" \ --data-urlencode "node_count=1" \ --data-urlencode "enable_readable_secondaries=false" \ --data-urlencode "retention_window_in_days=7" \ -H "Authorization: Bearer $DATABRICKS_TOKEN" ``` ### Response #### Success Response (200) - **instance** (string) - The name of the created instance. - **catalog** (string) - The name of the created catalog. - **synced_table** (string) - The ID of the synced pipeline. - **message** (string) - A confirmation message with a link to monitor progress. ``` -------------------------------- ### Project Dependencies for Dashboard Embedding Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/reflex/bi/embed_dashboard.mdx List the required Python packages for the dashboard embedding recipe. Ensure these are installed in your environment. ```python databricks-sdk requests reflex ``` -------------------------------- ### OBO Authentication and Query Execution Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/reflex/authentication/users_obo.mdx This snippet shows how to establish an on-behalf-of-user connection to Databricks SQL, execute a query, and process the results using the user's token. It includes functions for retrieving the user token from headers, connecting to the SQL warehouse, and fetching data. The Reflex state manages the application's UI and data flow, including loading states and error handling. Caching of the SQL connection is implemented for efficiency. ```python import reflex as rx import pandas as pd from databricks import sql from databricks.sdk.core import Config cfg = Config() _connection = None def get_user_token(headers): return getattr(headers, "x_forwarded_access_token", "") def connect_with_obo(http_path: str, user_token: str): global _connection if _connection: return _connection _connection = sql.connect( server_hostname=cfg.host, http_path=http_path, access_token=user_token ) return _connection def execute_query(table_name: str, conn): with conn.cursor() as cursor: query = f"SELECT * FROM {table_name} LIMIT 10" cursor.execute(query) return cursor.fetchall_arrow().to_pandas() class OboState(rx.State): warehouse_paths: dict[str, str] = {} selected_warehouse: str = "" table_name: str = "samples.nyctaxi.trips" data: list[list] = [] columns: list[dict] = [] is_loading: bool = False error_message: str = "" @rx.event(background=True) async def run_query(self): async with self: self.is_loading = True self.error_message = "" headers = self.router.headers user_token = get_user_token(headers) if not user_token: async with self: self.error_message = "No OBO token found." self.is_loading = False return try: http_path = self.warehouse_paths.get(self.selected_warehouse) conn = connect_with_obo(http_path, user_token) df = execute_query(self.table_name, conn) # Process dataframe for display d = df.values.tolist() c = [{"title": col, "id": col, "type": "str"} for col in df.columns] async with self: self.data = d self.columns = c except Exception as e: async with self: self.error_message = str(e) finally: async with self: self.is_loading = False ``` -------------------------------- ### Create Lakebase Resources Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_resources_create.mdx Use this code to create Lakebase resources, including a Databricks instance, a catalog, and a synced table pipeline. This example is shortened for brevity and not suitable for production use. ```python message = f"Resources created successfully. Synced table pipeline initiated. Check pipelines in workspace: {workspace_url}/pipelines" return LakebaseResourcesResponse( instance=instance_create.name, catalog=database_create.name, synced_table=pipeline_id, message=message, ) ``` -------------------------------- ### Get Specific Order by Key Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/building_endpoints/lakebase/lakebase_orders.mdx Retrieves a single order by its unique key. Useful for fetching details of a specific order. ```APIDOC ## GET /{order_key} ### Description Retrieves a specific order using its unique order key. ### Method GET ### Endpoint /{order_key} ### Parameters #### Path Parameters - **order_key** (int) - Required - The unique key of the order to retrieve. ### Response #### Success Response (200) - **o_orderkey** (int) - The unique key of the order. - **o_custkey** (int) - The key of the customer who placed the order. - **o_orderstatus** (string) - The current status of the order. - **o_orderpriority** (string) - The priority of the order. - **o_orderdate** (string) - The date the order was placed (ISO format). - **o_clerk** (string) - The name of the clerk who took the order. - **o_shippriority** (int) - The shipping priority. - **o_comment** (string) - Any comments related to the order. #### Response Example ```json { "o_orderkey": 1, "o_custkey": 10, "o_orderstatus": "O", "o_orderpriority": "1-URGENT", "o_orderdate": "2023-01-01T00:00:00", "o_clerk": "Clerk A", "o_shippriority": 0, "o_comment": "" } ``` ```