### 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 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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) ``` -------------------------------- ### 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** ``` -------------------------------- ### 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. ``` -------------------------------- ### 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" ``` -------------------------------- ### 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")) ``` -------------------------------- ### 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 ``` -------------------------------- ### Run Streamlit App Locally Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/blog/2025-03-17-dabs/2025-03-17-dabs.mdx Start the Streamlit application on your local machine for development and testing. ```bash streamlit run src/app/app.py ``` -------------------------------- ### app.py Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/dash/volumes/volumes_download.mdx Downloads a file from a Unity Catalog volume using the Databricks SDK. The file contents are read into memory. Ensure the Databricks SDK is installed. ```python from databricks.sdk import WorkspaceClient w = WorkspaceClient() download_file_path = "/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) ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Databricks Apps Configuration Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/create.mdx Configure the command to run your FastAPI application using uvicorn in the `app.yaml` file. This is used by Databricks Apps to start your application. ```yaml command: ["uvicorn", "app:app"] ``` -------------------------------- ### 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" ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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()) ``` -------------------------------- ### 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) ``` -------------------------------- ### app.py Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/reflex/volumes/volumes_download.mdx This snippet shows how to define a Reflex state to handle file downloads from a Unity Catalog volume. It uses the Databricks SDK to download the file content and then triggers a client-side download. ```python import reflex as rx import os from databricks.sdk import WorkspaceClient w = WorkspaceClient() class DownloadFileState(rx.State): download_file_path: str = "" async def handle_download(self): response = w.files.download(self.download_file_path) file_data = response.contents.read() file_name = os.path.basename(self.download_file_path) return rx.download(data=file_data, filename=file_name) ``` -------------------------------- ### 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") ``` -------------------------------- ### 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) ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ] } ``` ``` -------------------------------- ### 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 } ``` ``` -------------------------------- ### 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()) ``` -------------------------------- ### 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() ``` -------------------------------- ### 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 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 ``` -------------------------------- ### 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" } ``` -------------------------------- ### Python Dependencies for Video Streaming App 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 from Unity Catalog volumes. This includes FastAPI for the web framework, requests for making HTTP calls, and uvicorn as the ASGI server. ```python fastapi requests uvicorn ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 } } ``` ``` -------------------------------- ### 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, ) ``` -------------------------------- ### 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 } } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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": "" } ``` ``` -------------------------------- ### 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 from the database. Handles potential errors during the database query. ```python import logging from config.database import get_async_db from models.orders import ( CursorPaginationInfo, Order, OrderCount, OrderListCursorResponse, OrderListResponse, OrderRead, OrderSample, OrderStatusUpdate, OrderStatusUpdateResponse, PaginationInfo, ) from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from fastapi import APIRouter, Depends, HTTPException, Query logger = logging.getLogger(__name__) router = APIRouter(tags=["orders"]) # 1. GET ORDERS COUNT @router.get("/count", response_model=OrderCount, summary="Get total order count") async def get_order_count(db: AsyncSession = Depends(get_async_db)): try: stmt = select(func.count(Order.o_orderkey)) result = await db.execute(stmt) count = result.scalar() return OrderCount(total_orders=count) except Exception as e: logger.error(f"Error getting order count: {e}") raise HTTPException(status_code=500, detail="Failed to retrieve order count") ``` -------------------------------- ### Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/reflex/aiml/mcp_connect.mdx Lists the necessary Python packages for the project, including the Databricks SDK, Reflex, and MCP CLI. ```python databricks-sdk reflex mcp[cli] ``` -------------------------------- ### Initialize 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 initializes the connection to the GitHub MCP server. It requires an access token from the headers and uses the Databricks SDK to make an HTTP request to the specified connection. It extracts and returns the MCP Session ID from the response headers. ```python import contextvars import os import uuid from pathlib import Path from mcp.server.fastmcp import FastMCP from fastapi import FastAPI, Request from fastapi.responses import FileResponse from typing import Dict, Any from databricks.sdk import WorkspaceClient from databricks.sdk.service.serving import ExternalFunctionRequestHttpMethod STATIC_DIR = Path(__file__).parent / "static" # Create an MCP server mcp = FastMCP("Custom MCP Server on Databricks Apps") # Context variable for headers header_store = contextvars.ContextVar("header_store") def init_github_tools() -> Dict[str, Any]: headers = header_store.get({}) token=headers["x-forwarded-access-token"] json = { "jsonrpc": "2.0", "id": "init-1", "method": "initialize", "params": {} } try: response = WorkspaceClient(token=token, auth_type="pat").serving_endpoints.http_request( conn="github_u2m_connection", method=ExternalFunctionRequestHttpMethod.POST, path="/", json=json, ) except Exception as e: print(f"Error making the init request: {e}") return {"error": str(e)} # Extract the Mcp-Session-Id from response headers print("MCP_HEADERS", response.headers) session_id = response.headers.get("mcp-session-id") if not session_id: print("No session ID returned by server.") print(f"✅ Got MCP Session ID: {session_id}") return session_id ``` -------------------------------- ### Project Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/streamlit/bi/genie_api.mdx This file lists the required Python packages for the Streamlit application. Ensure these are installed in your environment to run the application correctly. ```python streamlit databricks-sdk pandas ``` -------------------------------- ### Application Dependencies Source: https://github.com/databricks-solutions/databricks-apps-cookbook/blob/main/docs/docs/fastapi/getting_started/create.mdx Specify FastAPI and uvicorn as dependencies in the `requirements.txt` file. This ensures that Databricks Apps installs the necessary packages for your application. ```python fastapi uvicorn ```