Sub topic 11
Sending scoring requests over REST
This chapter covers how to call a live Model Serving endpoint over HTTP. It assumes you have finished the previous chapters, so an endpoint named iris-endpoint exists and serves main.default.iris_classifier. It also assumes you know what an HTTP POST and a JSON body are, and that you can create a Databricks token (covered in the authentication chapter).
The invocation URL
Every serving endpoint has an invocations URL. It is built from the workspace host and the endpoint name:
https://<workspace-host>/serving-endpoints/<endpoint-name>/invocationsYou send an HTTP POST with two headers and a JSON body:
Authorization: Bearer <token>identifies the caller.Content-Type: application/jsontells the server how to parse the body.
The body must match the model's input signature, which you set when you logged the model. The endpoint passes your data to the model's predict method and returns the result as JSON.
Payload formats
The endpoint accepts several JSON layouts. Each one is a top-level key that says how your data is arranged.
| Key | Shape | Typical use |
|---|---|---|
| `dataframe_split` | `{"columns": [...], "data": [[...], ...]}` | Tabular models, compact for many rows |
| `dataframe_records` | `[{"col": value, ...}, ...]` | Tabular models, easy to read |
| `instances` | List of rows or tensors | Tensor-style input, one entry per example |
| `inputs` | Columns or tensors keyed by name | Tensor-style input, one entry per input |
Send exactly one of these keys per request. For a scikit-learn model with a column-based signature, dataframe_split and dataframe_records are the natural choices. Both produce the same pandas DataFrame inside the endpoint.
dataframe_split
The curl call from the topic plan sends one row in this format:
curl -X POST "https://<workspace-host>/serving-endpoints/iris-endpoint/invocations" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"dataframe_split": {"columns": ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"], "data": [[5.1, 3.5, 1.4, 0.2]]}}'A successful response has status 200 and a body like this:
{"predictions": [0]}predictions is a list with one entry per input row, in the same order. The class label 0 is setosa in the iris dataset.
dataframe_records
The same request with dataframe_records repeats the column names in every row, so it is longer. It is easier to read and to build from Python dictionaries:
{
"dataframe_records": [
{"sepal length (cm)": 5.1, "sepal width (cm)": 3.5, "petal length (cm)": 1.4, "petal width (cm)": 0.2},
{"sepal length (cm)": 6.7, "sepal width (cm)": 3.0, "petal length (cm)": 5.2, "petal width (cm)": 2.3}
]
}The response is {"predictions": [0, 2]}.
Why column names must match
The signature stored with the model lists each column name and type. The endpoint uses it to build the DataFrame and to check your input. Three mistakes cause most failures:
- Wrong or missing column names. The iris model was trained on columns such as
sepal length (cm), with spaces and parentheses.sepal_lengthfails. - Wrong types. A string such as
"5.1"in adoublecolumn can be rejected. Send numbers as JSON numbers. - Extra or missing columns. Schema enforcement raises an error when required columns are absent.
Calling the endpoint from Python
In an application you usually use an HTTP library. This script reads the host and token from environment variables so no secret is written in code. It also checks the status code and raises a readable error on failure.
import os
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/") # e.g. https://adb-123456.7.azuredatabricks.net
token = os.environ["DATABRICKS_TOKEN"]
url = f"{host}/serving-endpoints/iris-endpoint/invocations"
payload = {
"dataframe_records": [
{
"sepal length (cm)": 5.1,
"sepal width (cm)": 3.5,
"petal length (cm)": 1.4,
"petal width (cm)": 0.2,
},
{
"sepal length (cm)": 6.7,
"sepal width (cm)": 3.0,
"petal length (cm)": 5.2,
"petal width (cm)": 2.3,
},
]
}
response = requests.post(
url,
headers={"Authorization": f"Bearer {token}"},
json=payload, # requests sets Content-Type: application/json
timeout=60,
)
if not response.ok:
raise RuntimeError(f"{response.status_code}: {response.text}")
print(response.json()["predictions"])Passing json=payload makes requests serialize the dictionary and set the content type for you. Always set a timeout. Without one, a stalled connection blocks your program indefinitely.
Using the Databricks SDK
If you already use the SDK to create the endpoint, it can also query it. The SDK reads credentials from the environment or a configuration profile, so you do not build headers yourself:
from databricks.sdk import WorkspaceClient
w = WorkspaceClient()
result = w.serving_endpoints.query(
name="iris-endpoint",
dataframe_records=[
{
"sepal length (cm)": 5.1,
"sepal width (cm)": 3.5,
"petal length (cm)": 1.4,
"petal width (cm)": 0.2,
}
],
)
print(result.predictions)The SDK sends the same HTTP request underneath. Use it inside Databricks notebooks and jobs. Use plain REST from services that cannot install the SDK.
Reading error responses
When a request fails, the HTTP status code tells you which layer rejected it. The response body usually has an error_code and a message. Read the message before you change anything.
| Status | Usual cause | What to check |
|---|---|---|
| 400 | The payload does not match the signature, or the JSON is malformed | Column names, types, and the top-level key |
| 401 | Missing, expired, or invalid token | The `Authorization` header and the token's expiry |
| 403 | The token is valid but the caller lacks permission | The caller's `CAN QUERY` permission on the endpoint |
| 404 | No endpoint with that name, or the wrong host | The endpoint name and the workspace URL |
| 429 | Too many requests | Retry with backoff, or raise the endpoint's capacity |
| 5xx | The endpoint is starting, scaling, or the model code raised an error | Endpoint state and logs |
A 403 here is a different problem from a missing Unity Catalog privilege. Querying the endpoint needs permission on the endpoint. Creating the endpoint needed privileges on the model.
Cold starts and retries
If you enabled scale to zero when you created the endpoint, the endpoint releases its compute after a period without traffic. The first request after that wakes it up. The request can take much longer than normal, and it can fail with a 5xx status such as 503 while the endpoint scales out. A short retry loop with increasing waits handles this. Retry only on statuses that can clear on their own:
import os
import time
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
token = os.environ["DATABRICKS_TOKEN"]
url = f"{host}/serving-endpoints/iris-endpoint/invocations"
RETRYABLE = {429, 502, 503, 504}
def score(payload, attempts=5):
delay = 2
for attempt in range(1, attempts + 1):
response = requests.post(
url,
headers={"Authorization": f"Bearer {token}"},
json=payload,
timeout=120,
)
if response.ok:
return response.json()["predictions"]
if response.status_code not in RETRYABLE or attempt == attempts:
raise RuntimeError(f"{response.status_code}: {response.text}")
time.sleep(delay)
delay *= 2 # 2, 4, 8, 16 seconds
print(score({"dataframe_split": {
"columns": ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"],
"data": [[5.1, 3.5, 1.4, 0.2]],
}}))Do not retry 400, 401, 403, or 404. The same request will fail the same way. If low latency on the first call matters, turn off scale to zero and accept the cost of always-on compute.
Limits to design around
Endpoints enforce limits on request size, request duration, and request rate. At the time of writing, the documented request payload limit is 16 MB, and a single request must finish within a few minutes. Check the current Databricks documentation for exact values, because they differ by endpoint type and can change. Two practical rules follow:
- Batch rows in one request instead of sending one row per call. One request with 100 rows costs far less than 100 requests, and it stays well under the size limit.
- Use batch inference for large datasets. Scoring millions of rows through a REST endpoint is slow and expensive. Load the registered model in a job with
mlflow.pyfunc.load_modelinstead, using themodels:/main.default.iris_classifier@championURI from the versions chapter.
Summary of the request cycle
- Build the URL from the workspace host and endpoint name.
- Put a token in the
Authorization: Bearerheader. - Choose one payload key and match the signature's column names and types exactly.
- Check the status code, then read
predictionsfrom the JSON body. - Retry only on
429and transient5xxstatuses, with growing delays.
Exercise
A colleague sends {"dataframesplit": {"columns": ["sepallength", "sepalwidth", "petallength", "petal_width"], "data": [[5.1, 3.5, 1.4, 0.2]]}} to iris-endpoint and gets a 400 response. The token is valid and the endpoint is ready. What is the likely cause, and what is the fix?
Show answer
The column names do not match the model signature. The model was logged with names such as "sepal length (cm)", so schema enforcement rejects underscore names. Change the columns list to the exact names from the signature: "sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)".
Exercise
Your service calls an endpoint with scale to zero enabled. The first call each morning returns 503, and later calls succeed. Name two ways to deal with this, and say which status codes your retry loop must not retry.
Show answer
Add a retry loop with exponential backoff for transient statuses such as 429, 502, 503 and 504, or disable scale to zero so compute stays warm (at higher cost). The loop must not retry 400, 401, 403 or 404, because the same request will fail again until the payload, token, permissions, or endpoint name is fixed.