Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
name: CI
on:
push:
branches-ignore:
- 'generated'
- 'codegen/**'
- 'integrated/**'
- 'stl-preview-head/**'
- 'stl-preview-base/**'
branches:
- '**'
- '!integrated/**'
- '!stl-preview-head/**'
- '!stl-preview-base/**'
- '!generated'
- '!codegen/**'
- 'codegen/stl/**'
pull_request:
branches-ignore:
- 'stl-preview-head/**'
Expand All @@ -17,7 +19,7 @@ jobs:
timeout-minutes: 10
name: lint
runs-on: ${{ github.repository == 'stainless-sdks/openlayer-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }}
if: github.event_name == 'push' || github.event.pull_request.head.repo.fork
if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata')
steps:
- uses: actions/checkout@v6

Expand All @@ -36,7 +38,7 @@ jobs:
run: ./scripts/lint

build:
if: github.event_name == 'push' || github.event.pull_request.head.repo.fork
if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata')
timeout-minutes: 10
name: build
permissions:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.prism.log
.stdy.log
_dev

__pycache__
Expand Down
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.21.0"
".": "0.22.0"
}
33 changes: 33 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,39 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## 0.22.0 (2026-04-01)

Full Changelog: [v0.21.0...v0.22.0](https://github.com/openlayer-ai/openlayer-python/compare/v0.21.0...v0.22.0)

### Features

* **internal:** implement indices array format for query and form serialization ([e942e18](https://github.com/openlayer-ai/openlayer-python/commit/e942e184c2aa996816f3ce31dc63540bba1b4a67))


### Bug Fixes

* **deps:** bump minimum typing-extensions version ([d359d17](https://github.com/openlayer-ai/openlayer-python/commit/d359d17848a178449417287829dba2e3aba8e8b2))
* **pydantic:** do not pass `by_alias` unless set ([3679fc3](https://github.com/openlayer-ai/openlayer-python/commit/3679fc375ce6f06bfc1b73e810634de96435fa56))
* sanitize endpoint path params ([dc9d512](https://github.com/openlayer-ai/openlayer-python/commit/dc9d512d70c3543562e241d1ad13c32700d9e79a))


### Chores

* **ci:** skip lint on metadata-only changes ([e23a0d8](https://github.com/openlayer-ai/openlayer-python/commit/e23a0d85258132f481f2780516bdd60f37ae60d5))
* **internal:** tweak CI branches ([7e02151](https://github.com/openlayer-ai/openlayer-python/commit/7e021510e4a2abfe57e9634dcf561a55d52df23f))
* **internal:** update gitignore ([e96f24b](https://github.com/openlayer-ai/openlayer-python/commit/e96f24b7a87c928e0e276b728e67e887ed2b4f1f))
* **tests:** bump steady to v0.19.4 ([0ecf1e6](https://github.com/openlayer-ai/openlayer-python/commit/0ecf1e6b23fa9072b549325728ce7de83f0f8439))
* **tests:** bump steady to v0.19.5 ([757aae0](https://github.com/openlayer-ai/openlayer-python/commit/757aae03228cbeb6daea0094a0744bb5148fb05f))
* **tests:** bump steady to v0.19.6 ([95c72a9](https://github.com/openlayer-ai/openlayer-python/commit/95c72a92f27d3f8012a34567d134ee667663ee75))
* **tests:** bump steady to v0.19.7 ([16d4263](https://github.com/openlayer-ai/openlayer-python/commit/16d426396e70c2a9e81e61a8ed7b323a17c90e95))
* **tests:** bump steady to v0.20.1 ([6f06faf](https://github.com/openlayer-ai/openlayer-python/commit/6f06faf139d49d4ef42b1043f35ccb7c8653f067))
* **tests:** bump steady to v0.20.2 ([5c4116d](https://github.com/openlayer-ai/openlayer-python/commit/5c4116d7f56608a438e91593be3ab78ebff7e2e2))


### Refactors

* **tests:** switch from prism to steady ([0f01051](https://github.com/openlayer-ai/openlayer-python/commit/0f01051033b82d888ea3d3966fb1f49b338e92c4))

## 0.21.0 (2026-03-26)

Full Changelog: [v0.20.1...v0.21.0](https://github.com/openlayer-ai/openlayer-python/compare/v0.20.1...v0.21.0)
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ $ pip install ./path-to-wheel-file.whl

## Running tests

Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests.
Most tests require you to [set up a mock server](https://github.com/dgellow/steady) against the OpenAPI spec to run the tests.

```sh
$ ./scripts/mock
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "openlayer"
version = "0.21.0"
version = "0.22.0"
description = "The official Python library for the openlayer API"
dynamic = ["readme"]
license = "Apache-2.0"
Expand All @@ -11,7 +11,7 @@ authors = [
dependencies = [
"httpx>=0.23.0, <1",
"pydantic>=1.9.0, <3",
"typing-extensions>=4.10, <5",
"typing-extensions>=4.14, <5",
"anyio>=3.5.0, <5",
"distro>=1.7.0, <2",
"sniffio",
Expand Down
26 changes: 13 additions & 13 deletions scripts/mock
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,34 @@ fi

echo "==> Starting mock server with URL ${URL}"

# Run prism mock on the given spec
# Run steady mock on the given spec
if [ "$1" == "--daemon" ]; then
# Pre-install the package so the download doesn't eat into the startup timeout
npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism --version
npm exec --package=@stdy/cli@0.20.2 -- steady --version

npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log &
npm exec --package=@stdy/cli@0.20.2 -- steady --host 127.0.0.1 -p 4010 --validator-query-array-format=comma --validator-form-array-format=comma --validator-query-object-format=brackets --validator-form-object-format=brackets "$URL" &> .stdy.log &

# Wait for server to come online (max 30s)
# Wait for server to come online via health endpoint (max 30s)
echo -n "Waiting for server"
attempts=0
while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do
while ! curl --silent --fail "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1; do
if ! kill -0 $! 2>/dev/null; then
echo
cat .stdy.log
exit 1
fi
attempts=$((attempts + 1))
if [ "$attempts" -ge 300 ]; then
echo
echo "Timed out waiting for Prism server to start"
cat .prism.log
echo "Timed out waiting for Steady server to start"
cat .stdy.log
exit 1
fi
echo -n "."
sleep 0.1
done

if grep -q "✖ fatal" ".prism.log"; then
cat .prism.log
exit 1
fi

echo
else
npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL"
npm exec --package=@stdy/cli@0.20.2 -- steady --host 127.0.0.1 -p 4010 --validator-query-array-format=comma --validator-form-array-format=comma --validator-query-object-format=brackets --validator-form-object-format=brackets "$URL"
fi
16 changes: 8 additions & 8 deletions scripts/test
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

function prism_is_running() {
curl --silent "http://localhost:4010" >/dev/null 2>&1
function steady_is_running() {
curl --silent "http://127.0.0.1:4010/_x-steady/health" >/dev/null 2>&1
}

kill_server_on_port() {
Expand All @@ -25,7 +25,7 @@ function is_overriding_api_base_url() {
[ -n "$TEST_API_BASE_URL" ]
}

if ! is_overriding_api_base_url && ! prism_is_running ; then
if ! is_overriding_api_base_url && ! steady_is_running ; then
# When we exit this script, make sure to kill the background mock server process
trap 'kill_server_on_port 4010' EXIT

Expand All @@ -36,19 +36,19 @@ fi
if is_overriding_api_base_url ; then
echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}"
echo
elif ! prism_is_running ; then
echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server"
elif ! steady_is_running ; then
echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Steady server"
echo -e "running against your OpenAPI spec."
echo
echo -e "To run the server, pass in the path or url of your OpenAPI"
echo -e "spec to the prism command:"
echo -e "spec to the steady command:"
echo
echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}"
echo -e " \$ ${YELLOW}npm exec --package=@stdy/cli@0.20.2 -- steady path/to/your.openapi.yml --host 127.0.0.1 -p 4010 --validator-query-array-format=comma --validator-form-array-format=comma --validator-query-object-format=brackets --validator-form-object-format=brackets${NC}"
echo

exit 1
else
echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}"
echo -e "${GREEN}✔ Mock steady server is running with your OpenAPI spec${NC}"
echo
fi

Expand Down
9 changes: 8 additions & 1 deletion src/openlayer/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
from datetime import date, datetime
from typing_extensions import Self, Literal
from typing_extensions import Self, Literal, TypedDict

import pydantic
from pydantic.fields import FieldInfo
Expand Down Expand Up @@ -131,6 +131,10 @@ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
return model.model_dump_json(indent=indent)


class _ModelDumpKwargs(TypedDict, total=False):
by_alias: bool


def model_dump(
model: pydantic.BaseModel,
*,
Expand All @@ -142,6 +146,9 @@ def model_dump(
by_alias: bool | None = None,
) -> dict[str, Any]:
if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
kwargs: _ModelDumpKwargs = {}
if by_alias is not None:
kwargs["by_alias"] = by_alias
return model.model_dump(
mode=mode,
exclude=exclude,
Comment on lines +149 to 154
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 The _ModelDumpKwargs dict built in model_dump is never spread into model.model_dump() — the explicit by_alias=bool(by_alias) if by_alias is not None else False on line 159 remains, so by_alias=False is unconditionally passed to pydantic when the caller omits the argument. This completely defeats the stated fix ('pydantic: do not pass by_alias unless set') and silently overrides model-level alias_generator defaults in pydantic v2/v3; the fix is to replace the explicit by_alias kwarg with **kwargs.

Extended reasoning...

What the bug is

In src/openlayer/_compat.py, the PR introduces a _ModelDumpKwargs TypedDict and, inside the pydantic-v2 branch of model_dump, conditionally populates it:

kwargs: _ModelDumpKwargs = {}
if by_alias is not None:
    kwargs["by_alias"] = by_alias

However, the subsequent model.model_dump() call still contains the old explicit argument:

return model.model_dump(
    mode=mode,
    exclude=exclude,
    exclude_unset=exclude_unset,
    exclude_defaults=exclude_defaults,
    warnings=True if PYDANTIC_V1 else warnings,
    by_alias=bool(by_alias) if by_alias is not None else False,  # never removed
)

The kwargs dict is built but never spread — **kwargs is absent. It is completely dead code.

The specific code path that triggers it

Every call to model_dump(model) (the default case, by_alias=None) hits the pydantic v2 branch, builds an empty kwargs, and then calls model.model_dump(..., by_alias=False) because bool(by_alias) if by_alias is not None else False evaluates to False.

Why existing code does not prevent it

The kwargs TypedDict construction looks correct in isolation, which makes the bug easy to miss. The explicit by_alias=... keyword was never removed from the model.model_dump() call site when **kwargs was supposed to replace it. There are no tests verifying that by_alias is absent from forwarded kwargs when not explicitly set, so the regression went undetected.

Impact

Pydantic v2 models that rely on model-level alias configuration (e.g., model_config = ConfigDict(alias_generator=..., populate_by_name=True)) will have their alias behavior silently overridden whenever model_dump is called without an explicit by_alias argument. Fields will be serialized using their Python attribute names instead of the configured aliases, potentially breaking serialization for any SDK model that uses aliased field names.

How to fix it

Remove the explicit by_alias=bool(by_alias) if by_alias is not None else False kwarg and replace with **kwargs:

return model.model_dump(
    mode=mode,
    exclude=exclude,
    exclude_unset=exclude_unset,
    exclude_defaults=exclude_defaults,
    warnings=True if PYDANTIC_V1 else warnings,
    **kwargs,
)

Step-by-step proof

  1. Caller invokes model_dump(my_model) with no by_alias argument — defaults to None.
  2. Code enters the if (not PYDANTIC_V1) or hasattr(model, "model_dump"): branch.
  3. kwargs: _ModelDumpKwargs = {} is created; the if by_alias is not None: guard is False, so kwargs remains {}.
  4. model.model_dump(..., by_alias=bool(None) if None is not None else False) simplifies to model.model_dump(..., by_alias=False).
  5. Pydantic v2 receives an explicit by_alias=False, overriding any model-level alias_generator default.
  6. The kwargs dict is never referenced again and is garbage-collected at end of scope.

Expand Down
5 changes: 4 additions & 1 deletion src/openlayer/_qs.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ def _stringify_item(
items.extend(self._stringify_item(key, item, opts))
return items
elif array_format == "indices":
raise NotImplementedError("The array indices format is not supported yet")
items = []
for i, item in enumerate(value):
items.extend(self._stringify_item(f"{key}[{i}]", item, opts))
return items
elif array_format == "brackets":
items = []
key = key + "[]"
Expand Down
1 change: 1 addition & 0 deletions src/openlayer/_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from ._path import path_template as path_template
from ._sync import asyncify as asyncify
from ._proxy import LazyProxy as LazyProxy
from ._utils import (
Expand Down
127 changes: 127 additions & 0 deletions src/openlayer/_utils/_path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from __future__ import annotations

import re
from typing import (
Any,
Mapping,
Callable,
)
from urllib.parse import quote

# Matches '.' or '..' where each dot is either literal or percent-encoded (%2e / %2E).
_DOT_SEGMENT_RE = re.compile(r"^(?:\.|%2[eE]){1,2}$")

_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")


def _quote_path_segment_part(value: str) -> str:
"""Percent-encode `value` for use in a URI path segment.

Considers characters not in `pchar` set from RFC 3986 §3.3 to be unsafe.
https://datatracker.ietf.org/doc/html/rfc3986#section-3.3
"""
# quote() already treats unreserved characters (letters, digits, and -._~)
# as safe, so we only need to add sub-delims, ':', and '@'.
# Notably, unlike the default `safe` for quote(), / is unsafe and must be quoted.
return quote(value, safe="!$&'()*+,;=:@")


def _quote_query_part(value: str) -> str:
"""Percent-encode `value` for use in a URI query string.

Considers &, = and characters not in `query` set from RFC 3986 §3.4 to be unsafe.
https://datatracker.ietf.org/doc/html/rfc3986#section-3.4
"""
return quote(value, safe="!$'()*+,;:@/?")


def _quote_fragment_part(value: str) -> str:
"""Percent-encode `value` for use in a URI fragment.

Considers characters not in `fragment` set from RFC 3986 §3.5 to be unsafe.
https://datatracker.ietf.org/doc/html/rfc3986#section-3.5
"""
return quote(value, safe="!$&'()*+,;=:@/?")


def _interpolate(
template: str,
values: Mapping[str, Any],
quoter: Callable[[str], str],
) -> str:
"""Replace {name} placeholders in `template`, quoting each value with `quoter`.

Placeholder names are looked up in `values`.

Raises:
KeyError: If a placeholder is not found in `values`.
"""
# re.split with a capturing group returns alternating
# [text, name, text, name, ..., text] elements.
parts = _PLACEHOLDER_RE.split(template)

for i in range(1, len(parts), 2):
name = parts[i]
if name not in values:
raise KeyError(f"a value for placeholder {{{name}}} was not provided")
val = values[name]
if val is None:
parts[i] = "null"
elif isinstance(val, bool):
parts[i] = "true" if val else "false"
else:
parts[i] = quoter(str(values[name]))

return "".join(parts)


def path_template(template: str, /, **kwargs: Any) -> str:
"""Interpolate {name} placeholders in `template` from keyword arguments.

Args:
template: The template string containing {name} placeholders.
**kwargs: Keyword arguments to interpolate into the template.

Returns:
The template with placeholders interpolated and percent-encoded.

Safe characters for percent-encoding are dependent on the URI component.
Placeholders in path and fragment portions are percent-encoded where the `segment`
and `fragment` sets from RFC 3986 respectively are considered safe.
Placeholders in the query portion are percent-encoded where the `query` set from
RFC 3986 §3.3 is considered safe except for = and & characters.

Raises:
KeyError: If a placeholder is not found in `kwargs`.
ValueError: If resulting path contains /./ or /../ segments (including percent-encoded dot-segments).
"""
# Split the template into path, query, and fragment portions.
fragment_template: str | None = None
query_template: str | None = None

Comment on lines +99 to +101
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Inside path_template(), the local variable path_template = rest (line ~107) shadows the enclosing function name for the rest of the function scope. While the current code works correctly because the name is never used after assignment to call the function, any future code added inside this function that tries to call path_template(...) would get a TypeError: str object is not callable instead of the expected function call. Rename the variable to path_str or path_portion to eliminate the shadowing.

Extended reasoning...

In src/openlayer/_utils/_path.py, the newly introduced function path_template contains this assignment near the end of its setup block:

path_template = rest

This assigns a local string variable with the exact same name as the enclosing function. In Python, a name is determined to be local to a function at compile time - if Python sees any assignment to path_template anywhere in the function body, the entire function body treats path_template as a local variable. This means the module-level function object is completely inaccessible inside path_template() after the assignment.

The specific code path is: the function splits the input template into path, query, and fragment portions (rest = template, then optional splits on # and ?), and then assigns path_template = rest to hold the path portion. This string is then passed to _interpolate(path_template, kwargs, _quote_path_segment_part) on the very next statement.

The existing code is safe only because: (1) the function is not recursive and does not need to call itself, and (2) the local variable path_template (the string) is only accessed on the line immediately following its assignment, strictly after it has been bound. There is no window where an UnboundLocalError can occur in the current code.

However, this is an error-prone pattern with real maintenance risks. If a developer later adds code inside this function body and writes path_template(...), Python will raise TypeError: 'str' object is not callable (if after the assignment) or UnboundLocalError: local variable 'path_template' referenced before assignment (if before). Both errors would be confusing because the name visually looks like a function reference. Static analysis tools like pyright also flag this shadowing.

Step-by-step proof:

  1. Call path_template("/v1/{id}", id="abc").
  2. Inside the function, rest = "/v1/{id}", no # or ?, so no splits occur.
  3. path_template = rest assigns the string "/v1/{id}" to the local name path_template.
  4. _interpolate(path_template, ...) uses the local string - works fine currently.
  5. If a developer adds path_template(sub_template, ...) anywhere in this function after this PR, they will get a runtime error instead of a function call, because Python has already marked path_template as a local variable for the entire function scope.

Fix: rename the local variable to path_str or path_portion and update the single usage on the next line:

path_str = rest
path_result = _interpolate(path_str, kwargs, _quote_path_segment_part)

rest = template
if "#" in rest:
rest, fragment_template = rest.split("#", 1)
if "?" in rest:
rest, query_template = rest.split("?", 1)
path_template = rest

# Interpolate each portion with the appropriate quoting rules.
path_result = _interpolate(path_template, kwargs, _quote_path_segment_part)

# Reject dot-segments (. and ..) in the final assembled path. The check
# runs after interpolation so that adjacent placeholders or a mix of static
# text and placeholders that together form a dot-segment are caught.
# Also reject percent-encoded dot-segments to protect against incorrectly
# implemented normalization in servers/proxies.
for segment in path_result.split("/"):
if _DOT_SEGMENT_RE.match(segment):
raise ValueError(f"Constructed path {path_result!r} contains dot-segment {segment!r} which is not allowed")

result = path_result
if query_template is not None:
result += "?" + _interpolate(query_template, kwargs, _quote_query_part)
if fragment_template is not None:
result += "#" + _interpolate(fragment_template, kwargs, _quote_fragment_part)

return result
2 changes: 1 addition & 1 deletion src/openlayer/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

__title__ = "openlayer"
__version__ = "0.21.0" # x-release-please-version
__version__ = "0.22.0" # x-release-please-version
Loading