diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 00000000..ff261bad --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,9 @@ +ARG VARIANT="3.9" +FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} + +USER vscode + +RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.44.0" RYE_INSTALL_OPTION="--yes" bash +ENV PATH=/home/vscode/.rye/shims:$PATH + +RUN echo "[[ -d .venv ]] && source .venv/bin/activate || export PATH=\$PATH" >> /home/vscode/.bashrc diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000..c17fdc16 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,43 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/debian +{ + "name": "Debian", + "build": { + "dockerfile": "Dockerfile", + "context": ".." + }, + + "postStartCommand": "rye sync --all-features", + + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python" + ], + "settings": { + "terminal.integrated.shell.linux": "/bin/bash", + "python.pythonPath": ".venv/bin/python", + "python.defaultInterpreterPath": ".venv/bin/python", + "python.typeChecking": "basic", + "terminal.integrated.env.linux": { + "PATH": "/home/vscode/.rye/shims:${env:PATH}" + } + } + } + }, + "features": { + "ghcr.io/devcontainers/features/node:1": {} + } + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..b9241c38 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,104 @@ +name: CI +on: + push: + branches: + - '**' + - '!integrated/**' + - '!stl-preview-head/**' + - '!stl-preview-base/**' + - '!generated' + - '!codegen/**' + - 'codegen/stl/**' + pull_request: + branches-ignore: + - 'stl-preview-head/**' + - 'stl-preview-base/**' + +jobs: + lint: + timeout-minutes: 10 + name: lint + runs-on: ${{ startsWith(github.repository, 'stainless-sdks/') && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + 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@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Install Rye + run: | + curl -sSf https://rye.astral.sh/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: '0.44.0' + RYE_INSTALL_OPTION: '--yes' + + - name: Install dependencies + run: rye sync --all-features + + - name: Run lints + run: ./scripts/lint + + build: + 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: + contents: read + id-token: write + runs-on: ${{ startsWith(github.repository, 'stainless-sdks/') && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Install Rye + run: | + curl -sSf https://rye.astral.sh/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: '0.44.0' + RYE_INSTALL_OPTION: '--yes' + + - name: Install dependencies + run: rye sync --all-features + + - name: Run build + run: rye build + + - name: Get GitHub OIDC Token + if: |- + github.repository == 'stainless-sdks/courier-python' && + !startsWith(github.ref, 'refs/heads/stl/') + id: github-oidc + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: core.setOutput('github_token', await core.getIDToken()); + + - name: Upload tarball + if: |- + github.repository == 'stainless-sdks/courier-python' && + !startsWith(github.ref, 'refs/heads/stl/') + env: + URL: https://pkg.stainless.com/s + AUTH: ${{ steps.github-oidc.outputs.github_token }} + SHA: ${{ github.sha }} + run: ./scripts/utils/upload-artifact.sh + + test: + timeout-minutes: 10 + name: test + runs-on: ${{ startsWith(github.repository, 'stainless-sdks/') && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} + if: github.event_name == 'push' || github.event.pull_request.head.repo.fork + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Install Rye + run: | + curl -sSf https://rye.astral.sh/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: '0.44.0' + RYE_INSTALL_OPTION: '--yes' + + - name: Bootstrap + run: ./scripts/bootstrap + + - name: Run tests + run: ./scripts/test diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml new file mode 100644 index 00000000..b4012590 --- /dev/null +++ b/.github/workflows/publish-pypi.yml @@ -0,0 +1,31 @@ +# This workflow is triggered when a GitHub release is created. +# It can also be run manually to re-publish to PyPI in case it failed for some reason. +# You can run this workflow by navigating to https://www.github.com/trycourier/courier-python/actions/workflows/publish-pypi.yml +name: Publish PyPI +on: + workflow_dispatch: + + release: + types: [published] + +jobs: + publish: + name: publish + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Install Rye + run: | + curl -sSf https://rye.astral.sh/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: '0.44.0' + RYE_INSTALL_OPTION: '--yes' + + - name: Publish to PyPI + run: | + bash ./bin/publish-pypi + env: + PYPI_TOKEN: ${{ secrets.COURIER_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml new file mode 100644 index 00000000..4205e012 --- /dev/null +++ b/.github/workflows/release-doctor.yml @@ -0,0 +1,21 @@ +name: Release Doctor +on: + pull_request: + branches: + - main + workflow_dispatch: + +jobs: + release_doctor: + name: release doctor + runs-on: ubuntu-latest + if: github.repository == 'trycourier/courier-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') + + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Check release environment + run: | + bash ./bin/check-release-environment + env: + PYPI_TOKEN: ${{ secrets.COURIER_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..3824f4c4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.prism.log +.stdy.log +_dev + +__pycache__ +.mypy_cache + +dist + +.venv +.idea + +.env +.envrc +codegen.log +Brewfile.lock.json diff --git a/.python-version b/.python-version new file mode 100644 index 00000000..43077b24 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.9.18 diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 00000000..ebb8228f --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "7.26.0" +} \ No newline at end of file diff --git a/.stats.yml b/.stats.yml new file mode 100644 index 00000000..fbe74a9c --- /dev/null +++ b/.stats.yml @@ -0,0 +1,4 @@ +configured_endpoints: 145 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/courier/courier-82881993f19c5fac9ac662f1a516e5b54bd7c6655d07f29a3779dfb0286cafd3.yml +openapi_spec_hash: 92f4c510a5a15d091036d70caa8ee573 +config_hash: 768b0f5ada2bf01cf2659d5dbbad1fa0 diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..5b010307 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.analysis.importFormat": "relative", +} diff --git a/Brewfile b/Brewfile new file mode 100644 index 00000000..492ca37b --- /dev/null +++ b/Brewfile @@ -0,0 +1,2 @@ +brew "rye" + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..c774a81a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,121 @@ +## Setting up the environment + +### With Rye + +We use [Rye](https://rye.astral.sh/) to manage dependencies because it will automatically provision a Python environment with the expected Python version. To set it up, run: + +```sh +$ ./scripts/bootstrap +``` + +Or [install Rye manually](https://rye.astral.sh/guide/installation/) and run: + +```sh +$ rye sync --all-features +``` + +You can then run scripts using `rye run python script.py` or by activating the virtual environment: + +```sh +# Activate the virtual environment - https://docs.python.org/3/library/venv.html#how-venvs-work +$ source .venv/bin/activate + +# now you can omit the `rye run` prefix +$ python script.py +``` + +### Without Rye + +Alternatively if you don't want to install `Rye`, you can stick with the standard `pip` setup by ensuring you have the Python version specified in `.python-version`, create a virtual environment however you desire and then install dependencies using this command: + +```sh +$ pip install -r requirements-dev.lock +``` + +## Modifying/Adding code + +Most of the SDK is generated code. Modifications to code will be persisted between generations, but may +result in merge conflicts between manual patches and changes from the generator. The generator will never +modify the contents of the `src/courier/lib/` and `examples/` directories. + +## Adding and running examples + +All files in the `examples/` directory are not modified by the generator and can be freely edited or added to. + +```py +# add an example to examples/.py + +#!/usr/bin/env -S rye run python +… +``` + +```sh +$ chmod +x examples/.py +# run the example against your api +$ ./examples/.py +``` + +## Using the repository from source + +If you’d like to use the repository from source, you can either install from git or link to a cloned repository: + +To install via git: + +```sh +$ pip install git+ssh://git@github.com/trycourier/courier-python.git +``` + +Alternatively, you can build from source and install the wheel file: + +Building this package will create two files in the `dist/` directory, a `.tar.gz` containing the source files and a `.whl` that can be used to install the package efficiently. + +To create a distributable version of the library, all you have to do is run this command: + +```sh +$ rye build +# or +$ python -m build +``` + +Then to install: + +```sh +$ pip install ./path-to-wheel-file.whl +``` + +## Running tests + +```sh +$ ./scripts/test +``` + +## Linting and formatting + +This repository uses [ruff](https://github.com/astral-sh/ruff) and +[black](https://github.com/psf/black) to format the code in the repository. + +To lint: + +```sh +$ ./scripts/lint +``` + +To format and fix all ruff issues automatically: + +```sh +$ ./scripts/format +``` + +## Publishing and releases + +Changes made to this repository via the automated release PR pipeline should publish to PyPI automatically. If +the changes aren't made through the automated pipeline, you may want to make releases manually. + +### Publish with a GitHub workflow + +You can release to package managers by using [the `Publish PyPI` GitHub action](https://www.github.com/trycourier/courier-python/actions/workflows/publish-pypi.yml). This requires a setup organization or repository secret to be set up. + +### Publish manually + +If you need to manually release a package, you can run the `bin/publish-pypi` script with a `PYPI_TOKEN` set on +the environment. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..ca8054ae --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Courier + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index c49ce2b8..e7908ea3 100644 --- a/README.md +++ b/README.md @@ -1 +1,435 @@ -# courier-docs-python \ No newline at end of file +# Courier Python API library + + +[![PyPI version](https://img.shields.io/pypi/v/trycourier.svg?label=pypi%20(stable))](https://pypi.org/project/trycourier/) + +The Courier Python library provides convenient access to the Courier REST API from any Python 3.9+ +application. The library includes type definitions for all request params and response fields, +and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx). + +It is generated with [Stainless](https://www.stainless.com/). + +## Documentation + +The REST API documentation can be found on [www.courier.com](https://www.courier.com/docs). The full API of this library can be found in [api.md](api.md). + +## Installation + +```sh +# install from PyPI +pip install trycourier +``` + +## Usage + +The full API of this library can be found in [api.md](api.md). + +```python +import os +from courier import Courier + +client = Courier( + api_key=os.environ.get("COURIER_API_KEY"), # This is the default and can be omitted +) + +response = client.send.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, +) +print(response.request_id) +``` + +While you can provide an `api_key` keyword argument, +we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) +to add `COURIER_API_KEY="My API Key"` to your `.env` file +so that your API Key is not stored in source control. + +## Async usage + +Simply import `AsyncCourier` instead of `Courier` and use `await` with each API call: + +```python +import os +import asyncio +from courier import AsyncCourier + +client = AsyncCourier( + api_key=os.environ.get("COURIER_API_KEY"), # This is the default and can be omitted +) + + +async def main() -> None: + response = await client.send.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, + ) + print(response.request_id) + + +asyncio.run(main()) +``` + +Functionality between the synchronous and asynchronous clients is otherwise identical. + +### With aiohttp + +By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend. + +You can enable this by installing `aiohttp`: + +```sh +# install from PyPI +pip install trycourier[aiohttp] +``` + +Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`: + +```python +import os +import asyncio +from courier import DefaultAioHttpClient +from courier import AsyncCourier + + +async def main() -> None: + async with AsyncCourier( + api_key=os.environ.get("COURIER_API_KEY"), # This is the default and can be omitted + http_client=DefaultAioHttpClient(), + ) as client: + response = await client.send.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, + ) + print(response.request_id) + + +asyncio.run(main()) +``` + +## Using types + +Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like: + +- Serializing back into JSON, `model.to_json()` +- Converting to a dictionary, `model.to_dict()` + +Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`. + +## Nested params + +Nested parameters are dictionaries, typed using `TypedDict`, for example: + +```python +from courier import Courier + +client = Courier() + +response = client.send.message( + message={ + "data": {"foo": "bar"}, + "template": "template_id", + "to": {"user_id": "user_id"}, + }, +) +print(response.message) +``` + +## Handling errors + +When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `courier.APIConnectionError` is raised. + +When the API returns a non-success status code (that is, 4xx or 5xx +response), a subclass of `courier.APIStatusError` is raised, containing `status_code` and `response` properties. + +All errors inherit from `courier.APIError`. + +```python +import courier +from courier import Courier + +client = Courier() + +try: + client.send.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, + ) +except courier.APIConnectionError as e: + print("The server could not be reached") + print(e.__cause__) # an underlying Exception, likely raised within httpx. +except courier.RateLimitError as e: + print("A 429 status code was received; we should back off a bit.") +except courier.APIStatusError as e: + print("Another non-200-range status code was received") + print(e.status_code) + print(e.response) +``` + +Error codes are as follows: + +| Status Code | Error Type | +| ----------- | -------------------------- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| >=500 | `InternalServerError` | +| N/A | `APIConnectionError` | + +### Retries + +Certain errors are automatically retried 2 times by default, with a short exponential backoff. +Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, +429 Rate Limit, and >=500 Internal errors are all retried by default. + +You can use the `max_retries` option to configure or disable retry settings: + +```python +from courier import Courier + +# Configure the default for all requests: +client = Courier( + # default is 2 + max_retries=0, +) + +# Or, configure per-request: +client.with_options(max_retries=5).send.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, +) +``` + +### Timeouts + +By default requests time out after 1 minute. You can configure this with a `timeout` option, +which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object: + +```python +from courier import Courier + +# Configure the default for all requests: +client = Courier( + # 20 seconds (default is 1 minute) + timeout=20.0, +) + +# More granular control: +client = Courier( + timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), +) + +# Override per-request: +client.with_options(timeout=5.0).send.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, +) +``` + +On timeout, an `APITimeoutError` is thrown. + +Note that requests that time out are [retried twice by default](#retries). + +## Advanced + +### Logging + +We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. + +You can enable logging by setting the environment variable `COURIER_LOG` to `info`. + +```shell +$ export COURIER_LOG=info +``` + +Or to `debug` for more verbose logging. + +### How to tell whether `None` means `null` or missing + +In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`: + +```py +if response.my_field is None: + if 'my_field' not in response.model_fields_set: + print('Got json like {}, without a "my_field" key present at all.') + else: + print('Got json like {"my_field": null}.') +``` + +### Accessing raw response data (e.g. headers) + +The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g., + +```py +from courier import Courier + +client = Courier() +response = client.send.with_raw_response.message( + message={ + "to": { + "user_id": "your_user_id" + }, + "template": "your_template_id", + "data": { + "foo": "bar" + }, + }, +) +print(response.headers.get('X-My-Header')) + +send = response.parse() # get the object that `send.message()` would have returned +print(send.request_id) +``` + +These methods return an [`APIResponse`](https://github.com/trycourier/courier-python/tree/main/src/courier/_response.py) object. + +The async client returns an [`AsyncAPIResponse`](https://github.com/trycourier/courier-python/tree/main/src/courier/_response.py) with the same structure, the only difference being `await`able methods for reading the response content. + +#### `.with_streaming_response` + +The above interface eagerly reads the full response body when you make the request, which may not always be what you want. + +To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods. + +```python +with client.send.with_streaming_response.message( + message={ + "to": {"user_id": "your_user_id"}, + "template": "your_template_id", + "data": {"foo": "bar"}, + }, +) as response: + print(response.headers.get("X-My-Header")) + + for line in response.iter_lines(): + print(line) +``` + +The context manager is required so that the response will reliably be closed. + +### Making custom/undocumented requests + +This library is typed for convenient access to the documented API. + +If you need to access undocumented endpoints, params, or response properties, the library can still be used. + +#### Undocumented endpoints + +To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other +http verbs. Options on the client will be respected (such as retries) when making this request. + +```py +import httpx + +response = client.post( + "/foo", + cast_to=httpx.Response, + body={"my_param": True}, +) + +print(response.headers.get("x-foo")) +``` + +#### Undocumented request params + +If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request +options. + +#### Undocumented response properties + +To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You +can also get all the extra fields on the Pydantic model as a dict with +[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra). + +### Configuring the HTTP client + +You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: + +- Support for [proxies](https://www.python-httpx.org/advanced/proxies/) +- Custom [transports](https://www.python-httpx.org/advanced/transports/) +- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality + +```python +import httpx +from courier import Courier, DefaultHttpxClient + +client = Courier( + # Or use the `COURIER_BASE_URL` env var + base_url="http://my.test.server.example.com:8083", + http_client=DefaultHttpxClient( + proxy="http://my.test.proxy.example.com", + transport=httpx.HTTPTransport(local_address="0.0.0.0"), + ), +) +``` + +You can also customize the client on a per-request basis by using `with_options()`: + +```python +client.with_options(http_client=DefaultHttpxClient(...)) +``` + +### Managing HTTP resources + +By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting. + +```py +from courier import Courier + +with Courier() as client: + # make requests here + ... + +# HTTP client is now closed +``` + +## Versioning + +This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: + +1. Changes that only affect static types, without breaking runtime behavior. +2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ +3. Changes that we do not expect to impact the vast majority of users in practice. + +We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. + +We are keen for your feedback; please open an [issue](https://www.github.com/trycourier/courier-python/issues) with questions, bugs, or suggestions. + +### Determining the installed version + +If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version. + +You can determine the version that is being used at runtime with: + +```py +import courier +print(courier.__version__) +``` + +## Requirements + +Python 3.9 or higher. + +## Contributing + +See [the contributing documentation](./CONTRIBUTING.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..05c8e2b0 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,27 @@ +# Security Policy + +## Reporting Security Issues + +This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. + +To report a security issue, please contact the Stainless team at security@stainless.com. + +## Responsible Disclosure + +We appreciate the efforts of security researchers and individuals who help us maintain the security of +SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible +disclosure practices by allowing us a reasonable amount of time to investigate and address the issue +before making any information public. + +## Reporting Non-SDK Related Security Issues + +If you encounter security issues that are not directly related to SDKs but pertain to the services +or products provided by Courier, please follow the respective company's security reporting guidelines. + +### Courier Terms and Policies + +Please contact support@courier.com for any questions or concerns regarding the security of our services. + +--- + +Thank you for helping us keep the SDKs and systems they interact with secure. diff --git a/api.md b/api.md new file mode 100644 index 00000000..40c1c1ba --- /dev/null +++ b/api.md @@ -0,0 +1,706 @@ +# Shared Types + +```python +from courier.types import ( + AirshipProfile, + AirshipProfileAudience, + Alignment, + AudienceFilter, + AudienceFilterConfig, + AudienceRecipient, + Channel, + ChannelClassification, + ChannelMetadata, + ChannelPreference, + DeviceType, + Discord, + ElementalActionNodeWithType, + ElementalBaseNode, + ElementalChannelNode, + ElementalChannelNodeWithType, + ElementalContent, + ElementalContentSugar, + ElementalDividerNodeWithType, + ElementalHTMLNodeWithType, + ElementalImageNodeWithType, + ElementalMetaNodeWithType, + ElementalNode, + ElementalQuoteNodeWithType, + ElementalTextNodeWithType, + Expo, + FilterConfig, + Intercom, + IntercomRecipient, + ListFilter, + ListPatternRecipient, + ListRecipient, + MessageChannels, + MessageContext, + MessageProviders, + MessageProvidersType, + MessageRouting, + MessageRoutingChannel, + Metadata, + MsTeams, + MsTeamsBaseProperties, + MsTeamsRecipient, + MultipleTokens, + NotificationPreferenceDetails, + Pagerduty, + PagerdutyRecipient, + Paging, + Preference, + PreferenceStatus, + RecipientPreferences, + Rule, + SendDirectMessage, + SendToChannel, + SendToMsTeamsChannelID, + SendToMsTeamsChannelName, + SendToMsTeamsConversationID, + SendToMsTeamsEmail, + SendToMsTeamsUserID, + SendToSlackChannel, + SendToSlackEmail, + SendToSlackUserID, + Slack, + SlackBaseProperties, + SlackRecipient, + TextStyle, + Timeouts, + Token, + UserProfile, + UserProfileFirebaseToken, + UserRecipient, + Utm, + WebhookAuthMode, + WebhookAuthentication, + WebhookMethod, + WebhookProfile, + WebhookProfileType, + WebhookRecipient, +) +``` + +# Send + +Types: + +```python +from courier.types import SendMessageResponse +``` + +Methods: + +- client.send.message(\*\*params) -> SendMessageResponse + +# Audiences + +Types: + +```python +from courier.types import ( + Audience, + AudienceUpdateResponse, + AudienceListResponse, + AudienceListMembersResponse, +) +``` + +Methods: + +- client.audiences.retrieve(audience_id) -> Audience +- client.audiences.update(audience_id, \*\*params) -> AudienceUpdateResponse +- client.audiences.list(\*\*params) -> AudienceListResponse +- client.audiences.delete(audience_id) -> None +- client.audiences.list_members(audience_id, \*\*params) -> AudienceListMembersResponse + +# Providers + +Types: + +```python +from courier.types import Provider, ProvidersCatalogEntry, ProviderListResponse +``` + +Methods: + +- client.providers.create(\*\*params) -> Provider +- client.providers.retrieve(id) -> Provider +- client.providers.update(id, \*\*params) -> Provider +- client.providers.list(\*\*params) -> ProviderListResponse +- client.providers.delete(id) -> None + +## Catalog + +Types: + +```python +from courier.types.providers import CatalogListResponse +``` + +Methods: + +- client.providers.catalog.list(\*\*params) -> CatalogListResponse + +# AuditEvents + +Types: + +```python +from courier.types import AuditEvent, AuditEventListResponse +``` + +Methods: + +- client.audit_events.retrieve(audit_event_id) -> AuditEvent +- client.audit_events.list(\*\*params) -> AuditEventListResponse + +# Auth + +Types: + +```python +from courier.types import AuthIssueTokenResponse +``` + +Methods: + +- client.auth.issue_token(\*\*params) -> AuthIssueTokenResponse + +# Automations + +Types: + +```python +from courier.types import ( + AutomationInvokeResponse, + AutomationTemplate, + AutomationTemplateListResponse, +) +``` + +Methods: + +- client.automations.list(\*\*params) -> AutomationTemplateListResponse + +## Invoke + +Methods: + +- client.automations.invoke.invoke_ad_hoc(\*\*params) -> AutomationInvokeResponse +- client.automations.invoke.invoke_by_template(template_id, \*\*params) -> AutomationInvokeResponse + +# Journeys + +Types: + +```python +from courier.types import ( + CancelJourneyRequest, + CancelJourneyResponse, + CreateJourneyRequest, + Journey, + JourneyAINode, + JourneyAPIInvokeTriggerNode, + JourneyConditionAtom, + JourneyConditionGroup, + JourneyConditionNestedGroup, + JourneyConditionsField, + JourneyDelayDurationNode, + JourneyDelayUntilNode, + JourneyExitNode, + JourneyExperiment, + JourneyExperimentVariant, + JourneyFetchGetDeleteNode, + JourneyFetchPostPutNode, + JourneyMergeStrategy, + JourneyNode, + JourneyPublishRequest, + JourneyResponse, + JourneySegmentTriggerNode, + JourneySendNode, + JourneyState, + JourneyTemplateCreateRequest, + JourneyTemplateGetResponse, + JourneyTemplateListResponse, + JourneyTemplatePublishRequest, + JourneyTemplateReplaceRequest, + JourneyTemplateSummary, + JourneyThrottleDynamicNode, + JourneyThrottleStaticNode, + JourneyVersionItem, + JourneyVersionsListResponse, + JourneysInvokeRequest, + JourneysInvokeResponse, + JourneysListResponse, +) +``` + +Methods: + +- client.journeys.create(\*\*params) -> JourneyResponse +- client.journeys.retrieve(template_id, \*\*params) -> JourneyResponse +- client.journeys.list(\*\*params) -> JourneysListResponse +- client.journeys.archive(template_id) -> None +- client.journeys.cancel(\*\*params) -> CancelJourneyResponse +- client.journeys.invoke(template_id, \*\*params) -> JourneysInvokeResponse +- client.journeys.list_versions(template_id) -> JourneyVersionsListResponse +- client.journeys.publish(template_id, \*\*params) -> JourneyResponse +- client.journeys.replace(template_id, \*\*params) -> JourneyResponse + +## Templates + +Methods: + +- client.journeys.templates.create(template_id, \*\*params) -> JourneyTemplateGetResponse +- client.journeys.templates.retrieve(notification_id, \*, template_id) -> JourneyTemplateGetResponse +- client.journeys.templates.list(template_id, \*\*params) -> JourneyTemplateListResponse +- client.journeys.templates.archive(notification_id, \*, template_id) -> None +- client.journeys.templates.list_versions(notification_id, \*, template_id) -> NotificationTemplateVersionListResponse +- client.journeys.templates.publish(notification_id, \*, template_id, \*\*params) -> None +- client.journeys.templates.put_content(notification_id, \*, template_id, \*\*params) -> NotificationContentMutationResponse +- client.journeys.templates.put_locale(locale_id, \*, template_id, notification_id, \*\*params) -> NotificationContentMutationResponse +- client.journeys.templates.replace(notification_id, \*, template_id, \*\*params) -> JourneyTemplateGetResponse +- client.journeys.templates.retrieve_content(notification_id, \*, template_id, \*\*params) -> NotificationContentGetResponse + +# Broadcasts + +Types: + +```python +from courier.types import ( + Broadcast, + BroadcastListResponse, + BroadcastSchedule, + CreateBroadcastRequest, + ScheduleBroadcastRequest, + SendBroadcastRequest, + UpdateBroadcastRequest, +) +``` + +Methods: + +- client.broadcasts.create(\*\*params) -> Broadcast +- client.broadcasts.retrieve(broadcast_id) -> Broadcast +- client.broadcasts.update(broadcast_id, \*\*params) -> Broadcast +- client.broadcasts.list(\*\*params) -> BroadcastListResponse +- client.broadcasts.archive(broadcast_id) -> Broadcast +- client.broadcasts.cancel(broadcast_id) -> Broadcast +- client.broadcasts.duplicate(broadcast_id) -> Broadcast +- client.broadcasts.put_content(broadcast_id, \*\*params) -> NotificationContentMutationResponse +- client.broadcasts.retrieve_content(broadcast_id, \*\*params) -> NotificationContentGetResponse +- client.broadcasts.schedule(broadcast_id, \*\*params) -> Broadcast +- client.broadcasts.send(broadcast_id, \*\*params) -> Broadcast + +# Brands + +Types: + +```python +from courier.types import ( + Brand, + BrandColors, + BrandSettings, + BrandSettingsEmail, + BrandSettingsInApp, + BrandSnippet, + BrandSnippets, + BrandTemplate, + EmailFooter, + EmailHead, + EmailHeader, + Icons, + Logo, + WidgetBackground, + BrandListResponse, +) +``` + +Methods: + +- client.brands.create(\*\*params) -> Brand +- client.brands.retrieve(brand_id) -> Brand +- client.brands.update(brand_id, \*\*params) -> Brand +- client.brands.list(\*\*params) -> BrandListResponse +- client.brands.delete(brand_id) -> None + +# Digests + +Types: + +```python +from courier.types import DigestCategory, DigestInstance, DigestInstanceListResponse +``` + +## Schedules + +Methods: + +- client.digests.schedules.list_instances(schedule_id, \*\*params) -> DigestInstanceListResponse +- client.digests.schedules.release(schedule_id) -> None + +# Inbound + +Types: + +```python +from courier.types import InboundTrackEventResponse +``` + +Methods: + +- client.inbound.track_event(\*\*params) -> InboundTrackEventResponse + +# Lists + +Types: + +```python +from courier.types import PutSubscriptionsRecipient, SubscriptionList, ListListResponse +``` + +Methods: + +- client.lists.retrieve(list_id) -> SubscriptionList +- client.lists.update(list_id, \*\*params) -> None +- client.lists.list(\*\*params) -> ListListResponse +- client.lists.delete(list_id) -> None +- client.lists.restore(list_id) -> None + +## Subscriptions + +Types: + +```python +from courier.types.lists import SubscriptionListResponse +``` + +Methods: + +- client.lists.subscriptions.list(list_id, \*\*params) -> SubscriptionListResponse +- client.lists.subscriptions.add(list_id, \*\*params) -> None +- client.lists.subscriptions.subscribe(list_id, \*\*params) -> None +- client.lists.subscriptions.subscribe_user(user_id, \*, list_id, \*\*params) -> None +- client.lists.subscriptions.unsubscribe_user(user_id, \*, list_id) -> None + +# Messages + +Types: + +```python +from courier.types import ( + MessageDetails, + MessageRetrieveResponse, + MessageListResponse, + MessageContentResponse, + MessageHistoryResponse, + MessageResendResponse, +) +``` + +Methods: + +- client.messages.retrieve(message_id) -> MessageRetrieveResponse +- client.messages.list(\*\*params) -> MessageListResponse +- client.messages.cancel(message_id) -> MessageDetails +- client.messages.content(message_id) -> MessageContentResponse +- client.messages.history(message_id, \*\*params) -> MessageHistoryResponse +- client.messages.resend(message_id) -> MessageResendResponse + +# Requests + +Methods: + +- client.requests.archive(request_id) -> None + +# Notifications + +Types: + +```python +from courier.types import ( + BaseCheck, + Check, + ElementWithChecksums, + NotificationContentGetResponse, + NotificationContentMutationResponse, + NotificationContentPutRequest, + NotificationElementPutRequest, + NotificationGetContent, + NotificationLocalePutRequest, + NotificationTemplateAlias, + NotificationTemplateCreateRequest, + NotificationTemplatePayload, + NotificationTemplatePublishRequest, + NotificationTemplateResponse, + NotificationTemplateState, + NotificationTemplateSummary, + NotificationTemplateUpdateRequest, + NotificationTemplateVersionListResponse, + NotificationTemplateWritePayload, + VersionNode, + NotificationListResponse, + NotificationRetrieveContentResponse, +) +``` + +Methods: + +- client.notifications.create(\*\*params) -> NotificationTemplateResponse +- client.notifications.retrieve(id, \*\*params) -> NotificationTemplateResponse +- client.notifications.list(\*\*params) -> NotificationListResponse +- client.notifications.archive(id) -> None +- client.notifications.duplicate(id) -> NotificationTemplateResponse +- client.notifications.list_versions(id, \*\*params) -> NotificationTemplateVersionListResponse +- client.notifications.publish(id, \*\*params) -> None +- client.notifications.put_content(id, \*\*params) -> NotificationContentMutationResponse +- client.notifications.put_element(element_id, \*, id, \*\*params) -> NotificationContentMutationResponse +- client.notifications.put_locale(locale_id, \*, id, \*\*params) -> NotificationContentMutationResponse +- client.notifications.replace(id, \*\*params) -> NotificationTemplateResponse +- client.notifications.retrieve_content(id, \*\*params) -> NotificationRetrieveContentResponse + +## Checks + +Types: + +```python +from courier.types.notifications import CheckUpdateResponse, CheckListResponse +``` + +Methods: + +- client.notifications.checks.update(submission_id, \*, id, \*\*params) -> CheckUpdateResponse +- client.notifications.checks.list(submission_id, \*, id) -> CheckListResponse +- client.notifications.checks.delete(submission_id, \*, id) -> None + +# RoutingStrategies + +Types: + +```python +from courier.types import ( + AssociatedNotificationListResponse, + RoutingStrategyCreateRequest, + RoutingStrategyGetResponse, + RoutingStrategyListResponse, + RoutingStrategyReplaceRequest, + RoutingStrategySummary, +) +``` + +Methods: + +- client.routing_strategies.create(\*\*params) -> RoutingStrategyGetResponse +- client.routing_strategies.retrieve(id) -> RoutingStrategyGetResponse +- client.routing_strategies.list(\*\*params) -> RoutingStrategyListResponse +- client.routing_strategies.archive(id) -> None +- client.routing_strategies.list_notifications(id, \*\*params) -> AssociatedNotificationListResponse +- client.routing_strategies.replace(id, \*\*params) -> RoutingStrategyGetResponse + +# WorkspacePreferences + +Types: + +```python +from courier.types import ( + PublishPreferencesRequest, + PublishPreferencesResponse, + WorkspacePreferenceCreateRequest, + WorkspacePreferenceGetResponse, + WorkspacePreferenceListResponse, + WorkspacePreferenceReplaceRequest, + WorkspacePreferenceTopicCreateRequest, + WorkspacePreferenceTopicGetResponse, + WorkspacePreferenceTopicListResponse, + WorkspacePreferenceTopicReplaceRequest, +) +``` + +Methods: + +- client.workspace_preferences.create(\*\*params) -> WorkspacePreferenceGetResponse +- client.workspace_preferences.retrieve(section_id) -> WorkspacePreferenceGetResponse +- client.workspace_preferences.list() -> WorkspacePreferenceListResponse +- client.workspace_preferences.archive(section_id) -> None +- client.workspace_preferences.publish(\*\*params) -> PublishPreferencesResponse +- client.workspace_preferences.replace(section_id, \*\*params) -> WorkspacePreferenceGetResponse + +## Topics + +Methods: + +- client.workspace_preferences.topics.create(section_id, \*\*params) -> WorkspacePreferenceTopicGetResponse +- client.workspace_preferences.topics.retrieve(topic_id, \*, section_id) -> WorkspacePreferenceTopicGetResponse +- client.workspace_preferences.topics.list(section_id) -> WorkspacePreferenceTopicListResponse +- client.workspace_preferences.topics.archive(topic_id, \*, section_id) -> None +- client.workspace_preferences.topics.replace(topic_id, \*, section_id, \*\*params) -> WorkspacePreferenceTopicGetResponse + +# Profiles + +Types: + +```python +from courier.types import ( + SubscribeToListsRequestItem, + ProfileCreateResponse, + ProfileRetrieveResponse, + ProfileReplaceResponse, +) +``` + +Methods: + +- client.profiles.create(user_id, \*\*params) -> ProfileCreateResponse +- client.profiles.retrieve(user_id) -> ProfileRetrieveResponse +- client.profiles.update(user_id, \*\*params) -> None +- client.profiles.delete(user_id) -> None +- client.profiles.replace(user_id, \*\*params) -> ProfileReplaceResponse + +## Lists + +Types: + +```python +from courier.types.profiles import ListRetrieveResponse, ListDeleteResponse, ListSubscribeResponse +``` + +Methods: + +- client.profiles.lists.retrieve(user_id, \*\*params) -> ListRetrieveResponse +- client.profiles.lists.delete(user_id) -> ListDeleteResponse +- client.profiles.lists.subscribe(user_id, \*\*params) -> ListSubscribeResponse + +# Tenants + +Types: + +```python +from courier.types import ( + BaseTemplateTenantAssociation, + DefaultPreferences, + PostTenantTemplatePublishRequest, + PostTenantTemplatePublishResponse, + PutTenantTemplateRequest, + PutTenantTemplateResponse, + SubscriptionTopicNew, + Tenant, + TenantAssociation, + TenantTemplateInput, + TenantListResponse, + TenantListUsersResponse, +) +``` + +Methods: + +- client.tenants.retrieve(tenant_id) -> Tenant +- client.tenants.update(tenant_id, \*\*params) -> Tenant +- client.tenants.list(\*\*params) -> TenantListResponse +- client.tenants.delete(tenant_id) -> None +- client.tenants.list_users(tenant_id, \*\*params) -> TenantListUsersResponse + +## Preferences + +### Items + +Methods: + +- client.tenants.preferences.items.update(topic_id, \*, tenant_id, \*\*params) -> None +- client.tenants.preferences.items.delete(topic_id, \*, tenant_id) -> None + +## Templates + +Types: + +```python +from courier.types.tenants import TemplateListResponse +``` + +Methods: + +- client.tenants.templates.retrieve(template_id, \*, tenant_id) -> BaseTemplateTenantAssociation +- client.tenants.templates.list(tenant_id, \*\*params) -> TemplateListResponse +- client.tenants.templates.delete(template_id, \*, tenant_id) -> None +- client.tenants.templates.publish(template_id, \*, tenant_id, \*\*params) -> PostTenantTemplatePublishResponse +- client.tenants.templates.replace(template_id, \*, tenant_id, \*\*params) -> PutTenantTemplateResponse + +### Versions + +Methods: + +- client.tenants.templates.versions.retrieve(version, \*, tenant_id, template_id) -> BaseTemplateTenantAssociation + +# Translations + +Types: + +```python +from courier.types import TranslationRetrieveResponse +``` + +Methods: + +- client.translations.retrieve(locale, \*, domain) -> str +- client.translations.update(locale, \*, domain, \*\*params) -> None + +# Users + +## Preferences + +Types: + +```python +from courier.types.users import ( + BulkPreferenceTopic, + TopicPreference, + PreferenceRetrieveResponse, + PreferenceBulkReplaceResponse, + PreferenceBulkUpdateResponse, + PreferenceRetrieveTopicResponse, + PreferenceUpdateOrCreateTopicResponse, +) +``` + +Methods: + +- client.users.preferences.retrieve(user_id, \*\*params) -> PreferenceRetrieveResponse +- client.users.preferences.bulk_replace(user_id, \*\*params) -> PreferenceBulkReplaceResponse +- client.users.preferences.bulk_update(user_id, \*\*params) -> PreferenceBulkUpdateResponse +- client.users.preferences.delete_topic(topic_id, \*, user_id, \*\*params) -> None +- client.users.preferences.retrieve_topic(topic_id, \*, user_id, \*\*params) -> PreferenceRetrieveTopicResponse +- client.users.preferences.update_or_create_topic(topic_id, \*, user_id, \*\*params) -> PreferenceUpdateOrCreateTopicResponse + +## Tenants + +Types: + +```python +from courier.types.users import TenantListResponse +``` + +Methods: + +- client.users.tenants.list(user_id, \*\*params) -> TenantListResponse +- client.users.tenants.add_multiple(user_id, \*\*params) -> None +- client.users.tenants.add_single(tenant_id, \*, user_id, \*\*params) -> None +- client.users.tenants.remove_all(user_id) -> None +- client.users.tenants.remove_single(tenant_id, \*, user_id) -> None + +## Tokens + +Types: + +```python +from courier.types.users import UserToken, TokenRetrieveResponse, TokenListResponse +``` + +Methods: + +- client.users.tokens.retrieve(token, \*, user_id) -> TokenRetrieveResponse +- client.users.tokens.update(token, \*, user_id, \*\*params) -> None +- client.users.tokens.list(user_id) -> TokenListResponse +- client.users.tokens.delete(token, \*, user_id) -> None +- client.users.tokens.add_multiple(user_id) -> None +- client.users.tokens.add_single(token, \*, user_id, \*\*params) -> None diff --git a/bin/check-release-environment b/bin/check-release-environment new file mode 100644 index 00000000..b845b0f4 --- /dev/null +++ b/bin/check-release-environment @@ -0,0 +1,21 @@ +#!/usr/bin/env bash + +errors=() + +if [ -z "${PYPI_TOKEN}" ]; then + errors+=("The PYPI_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets.") +fi + +lenErrors=${#errors[@]} + +if [[ lenErrors -gt 0 ]]; then + echo -e "Found the following errors in the release environment:\n" + + for error in "${errors[@]}"; do + echo -e "- $error\n" + done + + exit 1 +fi + +echo "The environment is ready to push releases!" diff --git a/bin/publish-pypi b/bin/publish-pypi new file mode 100644 index 00000000..826054e9 --- /dev/null +++ b/bin/publish-pypi @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +set -eux +mkdir -p dist +rye build --clean +rye publish --yes --token=$PYPI_TOKEN diff --git a/examples/.keep b/examples/.keep new file mode 100644 index 00000000..d8c73e93 --- /dev/null +++ b/examples/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store example files demonstrating usage of this SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 00000000..53bca7ff --- /dev/null +++ b/noxfile.py @@ -0,0 +1,9 @@ +import nox + + +@nox.session(reuse_venv=True, name="test-pydantic-v1") +def test_pydantic_v1(session: nox.Session) -> None: + session.install("-r", "requirements-dev.lock") + session.install("pydantic<2") + + session.run("pytest", "--showlocals", "--ignore=tests/functional", *session.posargs) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..f3f5f014 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,269 @@ +[project] +name = "trycourier" +version = "7.26.0" +description = "The official Python library for the Courier API" +dynamic = ["readme"] +license = "Apache-2.0" +authors = [ +{ name = "Courier", email = "support@courier.com" }, +] + +dependencies = [ + "httpx>=0.23.0, <1", + "pydantic>=1.9.0, <3", + "typing-extensions>=4.14, <5", + "anyio>=3.5.0, <5", + "distro>=1.7.0, <2", + "sniffio", +] + +requires-python = ">= 3.9" +classifiers = [ + "Typing :: Typed", + "Intended Audience :: Developers", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Operating System :: OS Independent", + "Operating System :: POSIX", + "Operating System :: MacOS", + "Operating System :: POSIX :: Linux", + "Operating System :: Microsoft :: Windows", + "Topic :: Software Development :: Libraries :: Python Modules", + "License :: OSI Approved :: Apache Software License" +] + +[project.urls] +Homepage = "https://github.com/trycourier/courier-python" +Repository = "https://github.com/trycourier/courier-python" + +[project.optional-dependencies] +aiohttp = ["aiohttp", "httpx_aiohttp>=0.1.9"] + +[tool.rye] +managed = true +# version pins are in requirements-dev.lock +dev-dependencies = [ + "pyright==1.1.399", + "mypy==1.17", + "respx", + "pytest", + "pytest-asyncio", + "ruff", + "time-machine", + "nox", + "dirty-equals>=0.6.0", + "importlib-metadata>=6.7.0", + "rich>=13.7.1", + "pytest-xdist>=3.6.1", +] + +[tool.rye.scripts] +format = { chain = [ + "format:ruff", + "format:docs", + "fix:ruff", + # run formatting again to fix any inconsistencies when imports are stripped + "format:ruff", +]} +"format:docs" = "bash -c 'python scripts/utils/ruffen-docs.py README.md $(find . -type f -name api.md)'" +"format:ruff" = "ruff format" + +"lint" = { chain = [ + "check:ruff", + "typecheck", + "check:importable", +]} +"check:ruff" = "ruff check ." +"fix:ruff" = "ruff check --fix ." + +"check:importable" = "python -c 'import courier'" + +typecheck = { chain = [ + "typecheck:pyright", + "typecheck:mypy" +]} +"typecheck:pyright" = "pyright" +"typecheck:verify-types" = "pyright --verifytypes courier --ignoreexternal" +"typecheck:mypy" = "mypy ." + +[build-system] +requires = ["hatchling==1.26.3", "hatch-fancy-pypi-readme"] +build-backend = "hatchling.build" + +[tool.hatch.build] +include = [ + "src/*" +] + +[tool.hatch.build.targets.wheel] +packages = ["src/courier"] + +[tool.hatch.build.targets.sdist] +# Basically everything except hidden files/directories (such as .github, .devcontainers, .python-version, etc) +include = [ + "/*.toml", + "/*.json", + "/*.lock", + "/*.md", + "/mypy.ini", + "/noxfile.py", + "bin/*", + "examples/*", + "src/*", + "tests/*", +] + +[tool.hatch.metadata.hooks.fancy-pypi-readme] +content-type = "text/markdown" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +path = "README.md" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.substitutions]] +# replace relative links with absolute links +pattern = '\[(.+?)\]\(((?!https?://)\S+?)\)' +replacement = '[\1](https://github.com/trycourier/courier-python/tree/main/\g<2>)' + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "--tb=short -n auto" +xfail_strict = true +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "session" +filterwarnings = [ + "error" +] + +[tool.pyright] +# this enables practically every flag given by pyright. +# there are a couple of flags that are still disabled by +# default in strict mode as they are experimental and niche. +typeCheckingMode = "strict" +pythonVersion = "3.9" + +exclude = [ + "_dev", + ".venv", + ".nox", + ".git", +] + +reportImplicitOverride = true +reportOverlappingOverload = false + +reportImportCycles = false +reportPrivateUsage = false + +[tool.mypy] +pretty = true +show_error_codes = true + +# Exclude _files.py because mypy isn't smart enough to apply +# the correct type narrowing and as this is an internal module +# it's fine to just use Pyright. +# +# We also exclude our `tests` as mypy doesn't always infer +# types correctly and Pyright will still catch any type errors. +exclude = ["src/courier/_files.py", "_dev/.*.py", "tests/.*"] + +strict_equality = true +implicit_reexport = true +check_untyped_defs = true +no_implicit_optional = true + +warn_return_any = true +warn_unreachable = true +warn_unused_configs = true + +# Turn these options off as it could cause conflicts +# with the Pyright options. +warn_unused_ignores = false +warn_redundant_casts = false + +disallow_any_generics = true +disallow_untyped_defs = true +disallow_untyped_calls = true +disallow_subclassing_any = true +disallow_incomplete_defs = true +disallow_untyped_decorators = true +cache_fine_grained = true + +# By default, mypy reports an error if you assign a value to the result +# of a function call that doesn't return anything. We do this in our test +# cases: +# ``` +# result = ... +# assert result is None +# ``` +# Changing this codegen to make mypy happy would increase complexity +# and would not be worth it. +disable_error_code = "func-returns-value,overload-cannot-match" + +# https://github.com/python/mypy/issues/12162 +[[tool.mypy.overrides]] +module = "black.files.*" +ignore_errors = true +ignore_missing_imports = true + + +[tool.ruff] +line-length = 120 +output-format = "grouped" +target-version = "py38" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +select = [ + # isort + "I", + # bugbear rules + "B", + # remove unused imports + "F401", + # check for missing future annotations + "FA102", + # bare except statements + "E722", + # unused arguments + "ARG", + # print statements + "T201", + "T203", + # misuse of typing.TYPE_CHECKING + "TC004", + # import rules + "TID251", +] +ignore = [ + # mutable defaults + "B006", +] +unfixable = [ + # disable auto fix for print statements + "T201", + "T203", +] + +extend-safe-fixes = ["FA102"] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"functools.lru_cache".msg = "This function does not retain type information for the wrapped function's arguments; The `lru_cache` function from `_utils` should be used instead" + +[tool.ruff.lint.isort] +length-sort = true +length-sort-straight = true +combine-as-imports = true +extra-standard-library = ["typing_extensions"] +known-first-party = ["courier", "tests"] + +[tool.ruff.lint.per-file-ignores] +"bin/**.py" = ["T201", "T203"] +"scripts/**.py" = ["T201", "T203"] +"tests/**.py" = ["T201", "T203"] +"examples/**.py" = ["T201", "T203"] diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 00000000..eb8148d4 --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,66 @@ +{ + "packages": { + ".": {} + }, + "$schema": "https://raw.githubusercontent.com/stainless-api/release-please/main/schemas/config.json", + "include-v-in-tag": true, + "include-component-in-tag": false, + "versioning": "prerelease", + "prerelease": true, + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": false, + "pull-request-header": "Automated Release PR", + "pull-request-title-pattern": "release: ${version}", + "changelog-sections": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "perf", + "section": "Performance Improvements" + }, + { + "type": "revert", + "section": "Reverts" + }, + { + "type": "chore", + "section": "Chores" + }, + { + "type": "docs", + "section": "Documentation" + }, + { + "type": "style", + "section": "Styles" + }, + { + "type": "refactor", + "section": "Refactors" + }, + { + "type": "test", + "section": "Tests", + "hidden": true + }, + { + "type": "build", + "section": "Build System" + }, + { + "type": "ci", + "section": "Continuous Integration", + "hidden": true + } + ], + "release-type": "python", + "extra-files": [ + "src/courier/_version.py" + ] +} \ No newline at end of file diff --git a/requirements-dev.lock b/requirements-dev.lock new file mode 100644 index 00000000..9af7970f --- /dev/null +++ b/requirements-dev.lock @@ -0,0 +1,149 @@ +# generated by rye +# use `rye lock` or `rye sync` to update this lockfile +# +# last locked with the following flags: +# pre: false +# features: [] +# all-features: true +# with-sources: false +# generate-hashes: false +# universal: false + +-e file:. +aiohappyeyeballs==2.6.1 + # via aiohttp +aiohttp==3.13.3 + # via httpx-aiohttp + # via trycourier +aiosignal==1.4.0 + # via aiohttp +annotated-types==0.7.0 + # via pydantic +anyio==4.12.1 + # via httpx + # via trycourier +argcomplete==3.6.3 + # via nox +async-timeout==5.0.1 + # via aiohttp +attrs==25.4.0 + # via aiohttp + # via nox +backports-asyncio-runner==1.2.0 + # via pytest-asyncio +certifi==2026.1.4 + # via httpcore + # via httpx +colorlog==6.10.1 + # via nox +dependency-groups==1.3.1 + # via nox +dirty-equals==0.11 +distlib==0.4.0 + # via virtualenv +distro==1.9.0 + # via trycourier +exceptiongroup==1.3.1 + # via anyio + # via pytest +execnet==2.1.2 + # via pytest-xdist +filelock==3.19.1 + # via virtualenv +frozenlist==1.8.0 + # via aiohttp + # via aiosignal +h11==0.16.0 + # via httpcore +httpcore==1.0.9 + # via httpx +httpx==0.28.1 + # via httpx-aiohttp + # via respx + # via trycourier +httpx-aiohttp==0.1.12 + # via trycourier +humanize==4.13.0 + # via nox +idna==3.11 + # via anyio + # via httpx + # via yarl +importlib-metadata==8.7.1 +iniconfig==2.1.0 + # via pytest +markdown-it-py==3.0.0 + # via rich +mdurl==0.1.2 + # via markdown-it-py +multidict==6.7.0 + # via aiohttp + # via yarl +mypy==1.17.0 +mypy-extensions==1.1.0 + # via mypy +nodeenv==1.10.0 + # via pyright +nox==2025.11.12 +packaging==25.0 + # via dependency-groups + # via nox + # via pytest +pathspec==1.0.3 + # via mypy +platformdirs==4.4.0 + # via virtualenv +pluggy==1.6.0 + # via pytest +propcache==0.4.1 + # via aiohttp + # via yarl +pydantic==2.12.5 + # via trycourier +pydantic-core==2.41.5 + # via pydantic +pygments==2.19.2 + # via pytest + # via rich +pyright==1.1.399 +pytest==8.4.2 + # via pytest-asyncio + # via pytest-xdist +pytest-asyncio==1.2.0 +pytest-xdist==3.8.0 +python-dateutil==2.9.0.post0 + # via time-machine +respx==0.22.0 +rich==14.2.0 +ruff==0.14.13 +six==1.17.0 + # via python-dateutil +sniffio==1.3.1 + # via trycourier +time-machine==2.19.0 +tomli==2.4.0 + # via dependency-groups + # via mypy + # via nox + # via pytest +typing-extensions==4.15.0 + # via aiosignal + # via anyio + # via exceptiongroup + # via multidict + # via mypy + # via pydantic + # via pydantic-core + # via pyright + # via pytest-asyncio + # via trycourier + # via typing-inspection + # via virtualenv +typing-inspection==0.4.2 + # via pydantic +virtualenv==20.36.1 + # via nox +yarl==1.22.0 + # via aiohttp +zipp==3.23.0 + # via importlib-metadata diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 00000000..773b46f5 --- /dev/null +++ b/requirements.lock @@ -0,0 +1,76 @@ +# generated by rye +# use `rye lock` or `rye sync` to update this lockfile +# +# last locked with the following flags: +# pre: false +# features: [] +# all-features: true +# with-sources: false +# generate-hashes: false +# universal: false + +-e file:. +aiohappyeyeballs==2.6.1 + # via aiohttp +aiohttp==3.13.3 + # via httpx-aiohttp + # via trycourier +aiosignal==1.4.0 + # via aiohttp +annotated-types==0.7.0 + # via pydantic +anyio==4.12.1 + # via httpx + # via trycourier +async-timeout==5.0.1 + # via aiohttp +attrs==25.4.0 + # via aiohttp +certifi==2026.1.4 + # via httpcore + # via httpx +distro==1.9.0 + # via trycourier +exceptiongroup==1.3.1 + # via anyio +frozenlist==1.8.0 + # via aiohttp + # via aiosignal +h11==0.16.0 + # via httpcore +httpcore==1.0.9 + # via httpx +httpx==0.28.1 + # via httpx-aiohttp + # via trycourier +httpx-aiohttp==0.1.12 + # via trycourier +idna==3.11 + # via anyio + # via httpx + # via yarl +multidict==6.7.0 + # via aiohttp + # via yarl +propcache==0.4.1 + # via aiohttp + # via yarl +pydantic==2.12.5 + # via trycourier +pydantic-core==2.41.5 + # via pydantic +sniffio==1.3.1 + # via trycourier +typing-extensions==4.15.0 + # via aiosignal + # via anyio + # via exceptiongroup + # via multidict + # via pydantic + # via pydantic-core + # via trycourier + # via typing-inspection +typing-inspection==0.4.2 + # via pydantic +yarl==1.22.0 + # via aiohttp diff --git a/scripts/bootstrap b/scripts/bootstrap new file mode 100755 index 00000000..fe8451e4 --- /dev/null +++ b/scripts/bootstrap @@ -0,0 +1,27 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "${SKIP_BREW:-}" != "1" ] && [ -t 0 ]; then + brew bundle check >/dev/null 2>&1 || { + echo -n "==> Install Homebrew dependencies? (y/N): " + read -r response + case "$response" in + [yY][eE][sS]|[yY]) + brew bundle + ;; + *) + ;; + esac + echo + } +fi + +echo "==> Installing Python dependencies…" + +# experimental uv support makes installations significantly faster +rye config --set-bool behavior.use-uv=true + +rye sync --all-features diff --git a/scripts/format b/scripts/format new file mode 100755 index 00000000..667ec2d7 --- /dev/null +++ b/scripts/format @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +echo "==> Running formatters" +rye run format diff --git a/scripts/lint b/scripts/lint new file mode 100755 index 00000000..9776f4da --- /dev/null +++ b/scripts/lint @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if [ "$1" = "--fix" ]; then + echo "==> Running lints with --fix" + rye run fix:ruff +else + echo "==> Running lints" + rye run lint +fi + +echo "==> Making sure it imports" +rye run python -c 'import courier' diff --git a/scripts/test b/scripts/test new file mode 100755 index 00000000..39729d09 --- /dev/null +++ b/scripts/test @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + + + +export DEFER_PYDANTIC_BUILD=false + +echo "==> Running tests" +rye run pytest "$@" + +echo "==> Running Pydantic v1 tests" +rye run nox -s test-pydantic-v1 -- "$@" diff --git a/scripts/utils/ruffen-docs.py b/scripts/utils/ruffen-docs.py new file mode 100644 index 00000000..0cf2bd2f --- /dev/null +++ b/scripts/utils/ruffen-docs.py @@ -0,0 +1,167 @@ +# fork of https://github.com/asottile/blacken-docs adapted for ruff +from __future__ import annotations + +import re +import sys +import argparse +import textwrap +import contextlib +import subprocess +from typing import Match, Optional, Sequence, Generator, NamedTuple, cast + +MD_RE = re.compile( + r"(?P^(?P *)```\s*python\n)" r"(?P.*?)" r"(?P^(?P=indent)```\s*$)", + re.DOTALL | re.MULTILINE, +) +MD_PYCON_RE = re.compile( + r"(?P^(?P *)```\s*pycon\n)" r"(?P.*?)" r"(?P^(?P=indent)```.*$)", + re.DOTALL | re.MULTILINE, +) +PYCON_PREFIX = ">>> " +PYCON_CONTINUATION_PREFIX = "..." +PYCON_CONTINUATION_RE = re.compile( + rf"^{re.escape(PYCON_CONTINUATION_PREFIX)}( |$)", +) +DEFAULT_LINE_LENGTH = 100 + + +class CodeBlockError(NamedTuple): + offset: int + exc: Exception + + +def format_str( + src: str, +) -> tuple[str, Sequence[CodeBlockError]]: + errors: list[CodeBlockError] = [] + + @contextlib.contextmanager + def _collect_error(match: Match[str]) -> Generator[None, None, None]: + try: + yield + except Exception as e: + errors.append(CodeBlockError(match.start(), e)) + + def _md_match(match: Match[str]) -> str: + code = textwrap.dedent(match["code"]) + with _collect_error(match): + code = format_code_block(code) + code = textwrap.indent(code, match["indent"]) + return f"{match['before']}{code}{match['after']}" + + def _pycon_match(match: Match[str]) -> str: + code = "" + fragment = cast(Optional[str], None) + + def finish_fragment() -> None: + nonlocal code + nonlocal fragment + + if fragment is not None: + with _collect_error(match): + fragment = format_code_block(fragment) + fragment_lines = fragment.splitlines() + code += f"{PYCON_PREFIX}{fragment_lines[0]}\n" + for line in fragment_lines[1:]: + # Skip blank lines to handle Black adding a blank above + # functions within blocks. A blank line would end the REPL + # continuation prompt. + # + # >>> if True: + # ... def f(): + # ... pass + # ... + if line: + code += f"{PYCON_CONTINUATION_PREFIX} {line}\n" + if fragment_lines[-1].startswith(" "): + code += f"{PYCON_CONTINUATION_PREFIX}\n" + fragment = None + + indentation = None + for line in match["code"].splitlines(): + orig_line, line = line, line.lstrip() + if indentation is None and line: + indentation = len(orig_line) - len(line) + continuation_match = PYCON_CONTINUATION_RE.match(line) + if continuation_match and fragment is not None: + fragment += line[continuation_match.end() :] + "\n" + else: + finish_fragment() + if line.startswith(PYCON_PREFIX): + fragment = line[len(PYCON_PREFIX) :] + "\n" + else: + code += orig_line[indentation:] + "\n" + finish_fragment() + return code + + def _md_pycon_match(match: Match[str]) -> str: + code = _pycon_match(match) + code = textwrap.indent(code, match["indent"]) + return f"{match['before']}{code}{match['after']}" + + src = MD_RE.sub(_md_match, src) + src = MD_PYCON_RE.sub(_md_pycon_match, src) + return src, errors + + +def format_code_block(code: str) -> str: + return subprocess.check_output( + [ + sys.executable, + "-m", + "ruff", + "format", + "--stdin-filename=script.py", + f"--line-length={DEFAULT_LINE_LENGTH}", + ], + encoding="utf-8", + input=code, + ) + + +def format_file( + filename: str, + skip_errors: bool, +) -> int: + with open(filename, encoding="UTF-8") as f: + contents = f.read() + new_contents, errors = format_str(contents) + for error in errors: + lineno = contents[: error.offset].count("\n") + 1 + print(f"{filename}:{lineno}: code block parse error {error.exc}") + if errors and not skip_errors: + return 1 + if contents != new_contents: + print(f"{filename}: Rewriting...") + with open(filename, "w", encoding="UTF-8") as f: + f.write(new_contents) + return 0 + else: + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "-l", + "--line-length", + type=int, + default=DEFAULT_LINE_LENGTH, + ) + parser.add_argument( + "-S", + "--skip-string-normalization", + action="store_true", + ) + parser.add_argument("-E", "--skip-errors", action="store_true") + parser.add_argument("filenames", nargs="*") + args = parser.parse_args(argv) + + retv = 0 + for filename in args.filenames: + retv |= format_file(filename, skip_errors=args.skip_errors) + return retv + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/utils/upload-artifact.sh b/scripts/utils/upload-artifact.sh new file mode 100755 index 00000000..4b19bca6 --- /dev/null +++ b/scripts/utils/upload-artifact.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -exuo pipefail + +FILENAME=$(basename dist/*.whl) + +RESPONSE=$(curl -X POST "$URL?filename=$FILENAME" \ + -H "Authorization: Bearer $AUTH" \ + -H "Content-Type: application/json") + +SIGNED_URL=$(echo "$RESPONSE" | jq -r '.url') + +if [[ "$SIGNED_URL" == "null" ]]; then + echo -e "\033[31mFailed to get signed URL.\033[0m" + exit 1 +fi + +UPLOAD_RESPONSE=$(curl -v -X PUT \ + -H "Content-Type: binary/octet-stream" \ + --data-binary "@dist/$FILENAME" "$SIGNED_URL" 2>&1) + +if echo "$UPLOAD_RESPONSE" | grep -q "HTTP/[0-9.]* 200"; then + echo -e "\033[32mUploaded build to Stainless storage.\033[0m" + echo -e "\033[32mInstallation: pip install 'https://pkg.stainless.com/s/courier-python/$SHA/$FILENAME'\033[0m" +else + echo -e "\033[31mFailed to upload artifact.\033[0m" + exit 1 +fi diff --git a/src/courier/__init__.py b/src/courier/__init__.py new file mode 100644 index 00000000..74ee5621 --- /dev/null +++ b/src/courier/__init__.py @@ -0,0 +1,92 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import typing as _t + +from . import types +from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes, omit, not_given +from ._utils import file_from_path +from ._client import Client, Stream, Courier, Timeout, Transport, AsyncClient, AsyncStream, AsyncCourier, RequestOptions +from ._models import BaseModel +from ._version import __title__, __version__ +from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse +from ._constants import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_CONNECTION_LIMITS +from ._exceptions import ( + APIError, + CourierError, + ConflictError, + NotFoundError, + APIStatusError, + RateLimitError, + APITimeoutError, + BadRequestError, + APIConnectionError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + UnprocessableEntityError, + APIResponseValidationError, +) +from ._base_client import DefaultHttpxClient, DefaultAioHttpClient, DefaultAsyncHttpxClient +from ._utils._logs import setup_logging as _setup_logging + +__all__ = [ + "types", + "__version__", + "__title__", + "NoneType", + "Transport", + "ProxiesTypes", + "NotGiven", + "NOT_GIVEN", + "not_given", + "Omit", + "omit", + "CourierError", + "APIError", + "APIStatusError", + "APITimeoutError", + "APIConnectionError", + "APIResponseValidationError", + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", + "Timeout", + "RequestOptions", + "Client", + "AsyncClient", + "Stream", + "AsyncStream", + "Courier", + "AsyncCourier", + "file_from_path", + "BaseModel", + "DEFAULT_TIMEOUT", + "DEFAULT_MAX_RETRIES", + "DEFAULT_CONNECTION_LIMITS", + "DefaultHttpxClient", + "DefaultAsyncHttpxClient", + "DefaultAioHttpClient", +] + +if not _t.TYPE_CHECKING: + from ._utils._resources_proxy import resources as resources + +_setup_logging() + +# Update the __module__ attribute for exported symbols so that +# error messages point to this module instead of the module +# it was originally defined in, e.g. +# courier._exceptions.NotFoundError -> courier.NotFoundError +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + try: + __locals[__name].__module__ = "courier" + except (TypeError, AttributeError): + # Some of our exported symbols are builtins which we can't set attributes for. + pass diff --git a/src/courier/_base_client.py b/src/courier/_base_client.py new file mode 100644 index 00000000..00130ea1 --- /dev/null +++ b/src/courier/_base_client.py @@ -0,0 +1,2131 @@ +from __future__ import annotations + +import sys +import json +import time +import uuid +import email +import asyncio +import inspect +import logging +import platform +import warnings +import email.utils +from types import TracebackType +from random import random +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Type, + Union, + Generic, + Mapping, + TypeVar, + Iterable, + Iterator, + Optional, + Generator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Literal, override, get_origin + +import anyio +import httpx +import distro +import pydantic +from httpx import URL +from pydantic import PrivateAttr + +from . import _exceptions +from ._qs import Querystring +from ._files import to_httpx_files, async_to_httpx_files +from ._types import ( + Body, + Omit, + Query, + Headers, + Timeout, + NotGiven, + ResponseT, + AnyMapping, + PostParser, + BinaryTypes, + RequestFiles, + HttpxSendArgs, + RequestOptions, + AsyncBinaryTypes, + HttpxRequestFiles, + ModelBuilderProtocol, + not_given, +) +from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping +from ._compat import PYDANTIC_V1, model_copy, model_dump +from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type +from ._response import ( + APIResponse, + BaseAPIResponse, + AsyncAPIResponse, + extract_response_type, +) +from ._constants import ( + DEFAULT_TIMEOUT, + MAX_RETRY_DELAY, + DEFAULT_MAX_RETRIES, + INITIAL_RETRY_DELAY, + RAW_RESPONSE_HEADER, + OVERRIDE_CAST_TO_HEADER, + DEFAULT_CONNECTION_LIMITS, +) +from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder +from ._exceptions import ( + APIStatusError, + APITimeoutError, + APIConnectionError, + APIResponseValidationError, +) +from ._utils._json import openapi_dumps + +log: logging.Logger = logging.getLogger(__name__) + +# TODO: make base page type vars covariant +SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]") +AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]") + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +_StreamT = TypeVar("_StreamT", bound=Stream[Any]) +_AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any]) + +if TYPE_CHECKING: + from httpx._config import ( + DEFAULT_TIMEOUT_CONFIG, # pyright: ignore[reportPrivateImportUsage] + ) + + HTTPX_DEFAULT_TIMEOUT = DEFAULT_TIMEOUT_CONFIG +else: + try: + from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT + except ImportError: + # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366 + HTTPX_DEFAULT_TIMEOUT = Timeout(5.0) + + +class PageInfo: + """Stores the necessary information to build the request to retrieve the next page. + + Either `url` or `params` must be set. + """ + + url: URL | NotGiven + params: Query | NotGiven + json: Body | NotGiven + + @overload + def __init__( + self, + *, + url: URL, + ) -> None: ... + + @overload + def __init__( + self, + *, + params: Query, + ) -> None: ... + + @overload + def __init__( + self, + *, + json: Body, + ) -> None: ... + + def __init__( + self, + *, + url: URL | NotGiven = not_given, + json: Body | NotGiven = not_given, + params: Query | NotGiven = not_given, + ) -> None: + self.url = url + self.json = json + self.params = params + + @override + def __repr__(self) -> str: + if self.url: + return f"{self.__class__.__name__}(url={self.url})" + if self.json: + return f"{self.__class__.__name__}(json={self.json})" + return f"{self.__class__.__name__}(params={self.params})" + + +class BasePage(GenericModel, Generic[_T]): + """ + Defines the core interface for pagination. + + Type Args: + ModelT: The pydantic model that represents an item in the response. + + Methods: + has_next_page(): Check if there is another page available + next_page_info(): Get the necessary information to make a request for the next page + """ + + _options: FinalRequestOptions = PrivateAttr() + _model: Type[_T] = PrivateAttr() + + def has_next_page(self) -> bool: + items = self._get_page_items() + if not items: + return False + return self.next_page_info() is not None + + def next_page_info(self) -> Optional[PageInfo]: ... + + def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body] + ... + + def _params_from_url(self, url: URL) -> httpx.QueryParams: + # TODO: do we have to preprocess params here? + return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params) + + def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: + options = model_copy(self._options) + options._strip_raw_response_header() + + if not isinstance(info.params, NotGiven): + options.params = {**options.params, **info.params} + return options + + if not isinstance(info.url, NotGiven): + params = self._params_from_url(info.url) + url = info.url.copy_with(params=params) + options.params = dict(url.params) + options.url = str(url) + return options + + if not isinstance(info.json, NotGiven): + if not is_mapping(info.json): + raise TypeError("Pagination is only supported with mappings") + + if not options.json_data: + options.json_data = {**info.json} + else: + if not is_mapping(options.json_data): + raise TypeError("Pagination is only supported with mappings") + + options.json_data = {**options.json_data, **info.json} + return options + + raise ValueError("Unexpected PageInfo state") + + +class BaseSyncPage(BasePage[_T], Generic[_T]): + _client: SyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + client: SyncAPIClient, + model: Type[_T], + options: FinalRequestOptions, + ) -> None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + + self._model = model + self._client = client + self._options = options + + # Pydantic uses a custom `__iter__` method to support casting BaseModels + # to dictionaries. e.g. dict(model). + # As we want to support `for item in page`, this is inherently incompatible + # with the default pydantic behaviour. It is not possible to support both + # use cases at once. Fortunately, this is not a big deal as all other pydantic + # methods should continue to work as expected as there is an alternative method + # to cast a model to a dictionary, model.dict(), which is used internally + # by pydantic. + def __iter__(self) -> Iterator[_T]: # type: ignore + for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = page.get_next_page() + else: + return + + def get_next_page(self: SyncPageT) -> SyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return self._client._request_api_list(self._model, page=self.__class__, options=options) + + +class AsyncPaginator(Generic[_T, AsyncPageT]): + def __init__( + self, + client: AsyncAPIClient, + options: FinalRequestOptions, + page_cls: Type[AsyncPageT], + model: Type[_T], + ) -> None: + self._model = model + self._client = client + self._options = options + self._page_cls = page_cls + + def __await__(self) -> Generator[Any, None, AsyncPageT]: + return self._get_page().__await__() + + async def _get_page(self) -> AsyncPageT: + def _parser(resp: AsyncPageT) -> AsyncPageT: + resp._set_private_attributes( + model=self._model, + options=self._options, + client=self._client, + ) + return resp + + self._options.post_parser = _parser + + return await self._client.request(self._page_cls, self._options) + + async def __aiter__(self) -> AsyncIterator[_T]: + # https://github.com/microsoft/pyright/issues/3464 + page = cast( + AsyncPageT, + await self, # type: ignore + ) + async for item in page: + yield item + + +class BaseAsyncPage(BasePage[_T], Generic[_T]): + _client: AsyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + model: Type[_T], + client: AsyncAPIClient, + options: FinalRequestOptions, + ) -> None: + if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + + self._model = model + self._client = client + self._options = options + + async def __aiter__(self) -> AsyncIterator[_T]: + async for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = await page.get_next_page() + else: + return + + async def get_next_page(self: AsyncPageT) -> AsyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return await self._client._request_api_list(self._model, page=self.__class__, options=options) + + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]): + _client: _HttpxClientT + _version: str + _base_url: URL + max_retries: int + timeout: Union[float, Timeout, None] + _strict_response_validation: bool + _idempotency_header: str | None + _default_stream_cls: type[_DefaultStreamT] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None = DEFAULT_TIMEOUT, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + self._version = version + self._base_url = self._enforce_trailing_slash(URL(base_url)) + self.max_retries = max_retries + self.timeout = timeout + self._custom_headers = custom_headers or {} + self._custom_query = custom_query or {} + self._strict_response_validation = _strict_response_validation + self._idempotency_header = None + self._platform: Platform | None = None + + if max_retries is None: # pyright: ignore[reportUnnecessaryComparison] + raise TypeError( + "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `courier.DEFAULT_MAX_RETRIES`" + ) + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _make_status_error_from_response( + self, + response: httpx.Response, + ) -> APIStatusError: + if response.is_closed and not response.is_stream_consumed: + # We can't read the response body as it has been closed + # before it was read. This can happen if an event hook + # raises a status error. + body = None + err_msg = f"Error code: {response.status_code}" + else: + err_text = response.text.strip() + body = err_text + + try: + body = json.loads(err_text) + err_msg = f"Error code: {response.status_code} - {body}" + except Exception: + err_msg = err_text or f"Error code: {response.status_code}" + + return self._make_status_error(err_msg, body=body, response=response) + + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> _exceptions.APIStatusError: + raise NotImplementedError() + + def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0) -> httpx.Headers: + custom_headers = options.headers or {} + headers_dict = _merge_mappings(self.default_headers, custom_headers) + self._validate_headers(headers_dict, custom_headers) + + # headers are case-insensitive while dictionaries are not. + headers = httpx.Headers(headers_dict) + + idempotency_header = self._idempotency_header + if idempotency_header and options.idempotency_key and idempotency_header not in headers: + headers[idempotency_header] = options.idempotency_key + + # Don't set these headers if they were already set or removed by the caller. We check + # `custom_headers`, which can contain `Omit()`, instead of `headers` to account for the removal case. + lower_custom_headers = [header.lower() for header in custom_headers] + if "x-stainless-retry-count" not in lower_custom_headers: + headers["x-stainless-retry-count"] = str(retries_taken) + if "x-stainless-read-timeout" not in lower_custom_headers: + timeout = self.timeout if isinstance(options.timeout, NotGiven) else options.timeout + if isinstance(timeout, Timeout): + timeout = timeout.read + if timeout is not None: + headers["x-stainless-read-timeout"] = str(timeout) + + return headers + + def _prepare_url(self, url: str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + # Copied from httpx's `_merge_url` method. + merge_url = URL(url) + if merge_url.is_relative_url: + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + + return merge_url + + def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder: + return SSEDecoder() + + def _build_request( + self, + options: FinalRequestOptions, + *, + retries_taken: int = 0, + ) -> httpx.Request: + if log.isEnabledFor(logging.DEBUG): + log.debug( + "Request options: %s", + model_dump( + options, + exclude_unset=True, + # Pydantic v1 can't dump every type we support in content, so we exclude it for now. + exclude={ + "content", + } + if PYDANTIC_V1 + else {}, + ), + ) + kwargs: dict[str, Any] = {} + + json_data = options.json_data + if options.extra_json is not None: + if json_data is None: + json_data = cast(Body, options.extra_json) + elif is_mapping(json_data): + json_data = _merge_mappings(json_data, options.extra_json) + else: + raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`") + + headers = self._build_headers(options, retries_taken=retries_taken) + params = _merge_mappings(self.default_query, options.params) + content_type = headers.get("Content-Type") + files = options.files + + # If the given Content-Type header is multipart/form-data then it + # has to be removed so that httpx can generate the header with + # additional information for us as it has to be in this form + # for the server to be able to correctly parse the request: + # multipart/form-data; boundary=---abc-- + if content_type is not None and content_type.startswith("multipart/form-data"): + if "boundary" not in content_type: + # only remove the header if the boundary hasn't been explicitly set + # as the caller doesn't want httpx to come up with their own boundary + headers.pop("Content-Type") + + # As we are now sending multipart/form-data instead of application/json + # we need to tell httpx to use it, https://www.python-httpx.org/advanced/clients/#multipart-file-encoding + if json_data: + if not is_dict(json_data): + raise TypeError( + f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead." + ) + kwargs["data"] = self._serialize_multipartform(json_data) + + # httpx determines whether or not to send a "multipart/form-data" + # request based on the truthiness of the "files" argument. + # This gets around that issue by generating a dict value that + # evaluates to true. + # + # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186 + if not files: + files = cast(HttpxRequestFiles, ForceMultipartDict()) + + prepared_url = self._prepare_url(options.url) + # preserve hard-coded query params from the url + if params and prepared_url.query: + params = {**dict(prepared_url.params.items()), **params} + prepared_url = prepared_url.copy_with(raw_path=prepared_url.raw_path.split(b"?", 1)[0]) + if "_" in prepared_url.host: + # work around https://github.com/encode/httpx/discussions/2880 + kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")} + + is_body_allowed = options.method.lower() != "get" + + if is_body_allowed: + if options.content is not None and json_data is not None: + raise TypeError("Passing both `content` and `json_data` is not supported") + if options.content is not None and files is not None: + raise TypeError("Passing both `content` and `files` is not supported") + if options.content is not None: + kwargs["content"] = options.content + elif isinstance(json_data, bytes): + kwargs["content"] = json_data + elif not files: + # Don't set content when JSON is sent as multipart/form-data, + # since httpx's content param overrides other body arguments + kwargs["content"] = openapi_dumps(json_data) if is_given(json_data) and json_data is not None else None + kwargs["files"] = files + else: + headers.pop("Content-Type", None) + kwargs.pop("data", None) + + # TODO: report this error to httpx + return self._client.build_request( # pyright: ignore[reportUnknownMemberType] + headers=headers, + timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout, + method=options.method, + url=prepared_url, + # the `Query` type that we use is incompatible with qs' + # `Params` type as it needs to be typed as `Mapping[str, object]` + # so that passing a `TypedDict` doesn't cause an error. + # https://github.com/microsoft/pyright/issues/3526#event-6715453066 + params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None, + **kwargs, + ) + + def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]: + items = self.qs.stringify_items( + # TODO: type ignore is required as stringify_items is well typed but we can't be + # well typed without heavy validation. + data, # type: ignore + array_format="brackets", + ) + serialized: dict[str, object] = {} + for key, value in items: + existing = serialized.get(key) + + if not existing: + serialized[key] = value + continue + + # If a value has already been set for this key then that + # means we're sending data like `array[]=[1, 2, 3]` and we + # need to tell httpx that we want to send multiple values with + # the same key which is done by using a list or a tuple. + # + # Note: 2d arrays should never result in the same key at both + # levels so it's safe to assume that if the value is a list, + # it was because we changed it to be a list. + if is_list(existing): + existing.append(value) + else: + serialized[key] = [existing, value] + + return serialized + + def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]: + if not is_given(options.headers): + return cast_to + + # make a copy of the headers so we don't mutate user-input + headers = dict(options.headers) + + # we internally support defining a temporary header to override the + # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response` + # see _response.py for implementation details + override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, not_given) + if is_given(override_cast_to): + options.headers = headers + return cast(Type[ResponseT], override_cast_to) + + return cast_to + + def _should_stream_response_body(self, request: httpx.Request) -> bool: + return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return] + + def _process_response_data( + self, + *, + data: object, + cast_to: type[ResponseT], + response: httpx.Response, + ) -> ResponseT: + if data is None: + return cast(ResponseT, None) + + if cast_to is object: + return cast(ResponseT, data) + + try: + if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol): + return cast(ResponseT, cast_to.build(response=response, data=data)) + + if self._strict_response_validation: + return cast(ResponseT, validate_type(type_=cast_to, value=data)) + + return cast(ResponseT, construct_type(type_=cast_to, value=data)) + except pydantic.ValidationError as err: + raise APIResponseValidationError(response=response, body=data) from err + + @property + def qs(self) -> Querystring: + return Querystring() + + @property + def custom_auth(self) -> httpx.Auth | None: + return None + + @property + def auth_headers(self) -> dict[str, str]: + return {} + + @property + def default_headers(self) -> dict[str, str | Omit]: + return { + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": self.user_agent, + **self.platform_headers(), + **self.auth_headers, + **self._custom_headers, + } + + @property + def default_query(self) -> dict[str, object]: + return { + **self._custom_query, + } + + def _validate_headers( + self, + headers: Headers, # noqa: ARG002 + custom_headers: Headers, # noqa: ARG002 + ) -> None: + """Validate the given default headers and custom headers. + + Does nothing by default. + """ + return + + @property + def user_agent(self) -> str: + return f"{self.__class__.__name__}/Python {self._version}" + + @property + def base_url(self) -> URL: + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) + + def platform_headers(self) -> Dict[str, str]: + # the actual implementation is in a separate `lru_cache` decorated + # function because adding `lru_cache` to methods will leak memory + # https://github.com/python/cpython/issues/88476 + return platform_headers(self._version, platform=self._platform) + + def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None: + """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified. + + About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax + """ + if response_headers is None: + return None + + # First, try the non-standard `retry-after-ms` header for milliseconds, + # which is more precise than integer-seconds `retry-after` + try: + retry_ms_header = response_headers.get("retry-after-ms", None) + return float(retry_ms_header) / 1000 + except (TypeError, ValueError): + pass + + # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats). + retry_header = response_headers.get("retry-after") + try: + # note: the spec indicates that this should only ever be an integer + # but if someone sends a float there's no reason for us to not respect it + return float(retry_header) + except (TypeError, ValueError): + pass + + # Last, try parsing `retry-after` as a date. + retry_date_tuple = email.utils.parsedate_tz(retry_header) + if retry_date_tuple is None: + return None + + retry_date = email.utils.mktime_tz(retry_date_tuple) + return float(retry_date - time.time()) + + def _calculate_retry_timeout( + self, + remaining_retries: int, + options: FinalRequestOptions, + response_headers: Optional[httpx.Headers] = None, + ) -> float: + max_retries = options.get_max_retries(self.max_retries) + + # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says. + retry_after = self._parse_retry_after_header(response_headers) + if retry_after is not None and 0 < retry_after <= 60: + return retry_after + + # Also cap retry count to 1000 to avoid any potential overflows with `pow` + nb_retries = min(max_retries - remaining_retries, 1000) + + # Apply exponential backoff, but not more than the max. + sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY) + + # Apply some jitter, plus-or-minus half a second. + jitter = 1 - 0.25 * random() + timeout = sleep_seconds * jitter + return timeout if timeout >= 0 else 0 + + def _should_retry(self, response: httpx.Response) -> bool: + # Note: this is not a standard header + should_retry_header = response.headers.get("x-should-retry") + + # If the server explicitly says whether or not to retry, obey. + if should_retry_header == "true": + log.debug("Retrying as header `x-should-retry` is set to `true`") + return True + if should_retry_header == "false": + log.debug("Not retrying as header `x-should-retry` is set to `false`") + return False + + # Retry on request timeouts. + if response.status_code == 408: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry on lock timeouts. + if response.status_code == 409: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry on rate limits. + if response.status_code == 429: + log.debug("Retrying due to status code %i", response.status_code) + return True + + # Retry internal errors. + if response.status_code >= 500: + log.debug("Retrying due to status code %i", response.status_code) + return True + + log.debug("Not retrying") + return False + + def _idempotency_key(self) -> str: + return f"stainless-python-retry-{uuid.uuid4()}" + + +class _DefaultHttpxClient(httpx.Client): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultHttpxClient = httpx.Client + """An alias to `httpx.Client` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.Client` will result in httpx's defaults being used, not ours. + """ +else: + DefaultHttpxClient = _DefaultHttpxClient + + +class SyncHttpxClientWrapper(DefaultHttpxClient): + def __del__(self) -> None: + if self.is_closed: + return + + try: + self.close() + except Exception: + pass + + +class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]): + _client: httpx.Client + _default_stream_cls: type[Stream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.Client | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + _strict_response_validation: bool, + ) -> None: + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}" + ) + + super().__init__( + version=version, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + base_url=base_url, + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or SyncHttpxClientWrapper( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + ) + + def is_closed(self) -> bool: + return self._client.is_closed + + def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + # If an error is thrown while constructing a client, self._client + # may not be present + if hasattr(self, "_client"): + self._client.close() + + def __enter__(self: _T) -> _T: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> FinalRequestOptions: + """Hook for mutating the given options""" + return options + + def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: Type[_StreamT], + ) -> _StreamT: ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: Type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + cast_to = self._maybe_override_cast_to(cast_to, options) + + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + if input_options.idempotency_key is None and input_options.method.lower() != "get": + # ensure the idempotency key is reused between requests + input_options.idempotency_key = self._idempotency_key() + + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) + + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = self._prepare_options(options) + + remaining_retries = max_retries - retries_taken + request = self._build_request(options, retries_taken=retries_taken) + self._prepare_request(request) + + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + + if options.follow_redirects is not None: + kwargs["follow_redirects"] = options.follow_redirects + + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + + response = None + try: + response = self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + err.response.close() + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + err.response.read() + + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None + + break + + assert response is not None, "could not resolve response (should never happen)" + return self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + retries_taken=retries_taken, + ) + + def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken + if remaining_retries == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining_retries) + + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + time.sleep(timeout) + + def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, + ) -> ResponseT: + origin = get_origin(cast_to) or cast_to + + if ( + inspect.isclass(origin) + and issubclass(origin, BaseAPIResponse) + # we only want to actually return the custom BaseAPIResponse class if we're + # returning the raw response, or if we're not streaming SSE, as if we're streaming + # SSE then `cast_to` doesn't actively reflect the type we need to parse into + and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER))) + ): + if not issubclass(origin, APIResponse): + raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + ResponseT, + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = APIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return api_response.parse() + + def _request_api_list( + self, + model: Type[object], + page: Type[SyncPageT], + options: FinalRequestOptions, + ) -> SyncPageT: + def _parser(resp: SyncPageT) -> SyncPageT: + resp._set_private_attributes( + client=self, + model=model, + options=options, + ) + return resp + + options.post_parser = _parser + + return self.request(page, options, stream=False) + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + # cast is required because mypy complains about returning Any even though + # it understands the type variables + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: ... + + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: BinaryTypes | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options) + return self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[object], + page: Type[SyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> SyncPageT: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +class _DefaultAsyncHttpxClient(httpx.AsyncClient): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + super().__init__(**kwargs) + + +try: + import httpx_aiohttp +except ImportError: + + class _DefaultAioHttpClient(httpx.AsyncClient): + def __init__(self, **_kwargs: Any) -> None: + raise RuntimeError("To use the aiohttp client you must have installed the package with the `aiohttp` extra") +else: + + class _DefaultAioHttpClient(httpx_aiohttp.HttpxAiohttpClient): # type: ignore + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultAsyncHttpxClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.AsyncClient` will result in httpx's defaults being used, not ours. + """ + + DefaultAioHttpClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that changes the default HTTP transport to `aiohttp`.""" +else: + DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient + DefaultAioHttpClient = _DefaultAioHttpClient + + +class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient): + def __del__(self) -> None: + if self.is_closed: + return + + try: + # TODO(someday): support non asyncio runtimes here + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: + pass + + +class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]): + _client: httpx.AsyncClient + _default_stream_cls: type[AsyncStream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.AsyncClient | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.AsyncClient` but got {type(http_client)}" + ) + + super().__init__( + version=version, + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or AsyncHttpxClientWrapper( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + ) + + def is_closed(self) -> bool: + return self._client.is_closed + + async def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + await self._client.aclose() + + async def __aenter__(self: _T) -> _T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> FinalRequestOptions: + """Hook for mutating the given options""" + return options + + async def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + if self._platform is None: + # `get_platform` can make blocking IO calls so we + # execute it earlier while we are in an async context + self._platform = await asyncify(get_platform)() + + cast_to = self._maybe_override_cast_to(cast_to, options) + + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + if input_options.idempotency_key is None and input_options.method.lower() != "get": + # ensure the idempotency key is reused between requests + input_options.idempotency_key = self._idempotency_key() + + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) + + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = await self._prepare_options(options) + + remaining_retries = max_retries - retries_taken + request = self._build_request(options, retries_taken=retries_taken) + await self._prepare_request(request) + + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + + if options.follow_redirects is not None: + kwargs["follow_redirects"] = options.follow_redirects + + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + + response = None + try: + response = await self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + await err.response.aclose() + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + await err.response.aread() + + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None + + break + + assert response is not None, "could not resolve response (should never happen)" + return await self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + retries_taken=retries_taken, + ) + + async def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken + if remaining_retries == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining_retries) + + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + await anyio.sleep(timeout) + + async def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, + ) -> ResponseT: + origin = get_origin(cast_to) or cast_to + + if ( + inspect.isclass(origin) + and issubclass(origin, BaseAPIResponse) + # we only want to actually return the custom BaseAPIResponse class if we're + # returning the raw response, or if we're not streaming SSE, as if we're streaming + # SSE then `cast_to` doesn't actively reflect the type we need to parse into + and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER))) + ): + if not issubclass(origin, AsyncAPIResponse): + raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + "ResponseT", + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = AsyncAPIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + retries_taken=retries_taken, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return await api_response.parse() + + def _request_api_list( + self, + model: Type[_T], + page: Type[AsyncPageT], + options: FinalRequestOptions, + ) -> AsyncPaginator[_T, AsyncPageT]: + return AsyncPaginator(client=self, options=options, page_cls=page, model=model) + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: ... + + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + async def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="patch", + url=path, + json_data=body, + content=content, + files=await async_to_httpx_files(files), + **options, + ) + return await self.request(cast_to, opts) + + async def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if files is not None and content is not None: + raise TypeError("Passing both `files` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts) + + async def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + content: AsyncBinaryTypes | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + if body is not None and content is not None: + raise TypeError("Passing both `body` and `content` is not supported") + if isinstance(body, bytes): + warnings.warn( + "Passing raw bytes as `body` is deprecated and will be removed in a future version. " + "Please pass raw bytes via the `content` parameter instead.", + DeprecationWarning, + stacklevel=2, + ) + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options) + return await self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[_T], + page: Type[AsyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> AsyncPaginator[_T, AsyncPageT]: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +def make_request_options( + *, + query: Query | None = None, + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + idempotency_key: str | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + post_parser: PostParser | NotGiven = not_given, +) -> RequestOptions: + """Create a dict of type RequestOptions without keys of NotGiven values.""" + options: RequestOptions = {} + if extra_headers is not None: + options["headers"] = extra_headers + + if extra_body is not None: + options["extra_json"] = cast(AnyMapping, extra_body) + + if query is not None: + options["params"] = query + + if extra_query is not None: + options["params"] = {**options.get("params", {}), **extra_query} + + if not isinstance(timeout, NotGiven): + options["timeout"] = timeout + + if idempotency_key is not None: + options["idempotency_key"] = idempotency_key + + if is_given(post_parser): + # internal + options["post_parser"] = post_parser # type: ignore + + return options + + +class ForceMultipartDict(Dict[str, None]): + def __bool__(self) -> bool: + return True + + +class OtherPlatform: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"Other:{self.name}" + + +Platform = Union[ + OtherPlatform, + Literal[ + "MacOS", + "Linux", + "Windows", + "FreeBSD", + "OpenBSD", + "iOS", + "Android", + "Unknown", + ], +] + + +def get_platform() -> Platform: + try: + system = platform.system().lower() + platform_name = platform.platform().lower() + except Exception: + return "Unknown" + + if "iphone" in platform_name or "ipad" in platform_name: + # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7 + # system is Darwin and platform_name is a string like: + # - Darwin-21.6.0-iPhone12,1-64bit + # - Darwin-21.6.0-iPad7,11-64bit + return "iOS" + + if system == "darwin": + return "MacOS" + + if system == "windows": + return "Windows" + + if "android" in platform_name: + # Tested using Pydroid 3 + # system is Linux and platform_name is a string like 'Linux-5.10.81-android12-9-00001-geba40aecb3b7-ab8534902-aarch64-with-libc' + return "Android" + + if system == "linux": + # https://distro.readthedocs.io/en/latest/#distro.id + distro_id = distro.id() + if distro_id == "freebsd": + return "FreeBSD" + + if distro_id == "openbsd": + return "OpenBSD" + + return "Linux" + + if platform_name: + return OtherPlatform(platform_name) + + return "Unknown" + + +@lru_cache(maxsize=None) +def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]: + return { + "X-Stainless-Lang": "python", + "X-Stainless-Package-Version": version, + "X-Stainless-OS": str(platform or get_platform()), + "X-Stainless-Arch": str(get_architecture()), + "X-Stainless-Runtime": get_python_runtime(), + "X-Stainless-Runtime-Version": get_python_version(), + } + + +class OtherArch: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"other:{self.name}" + + +Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]] + + +def get_python_runtime() -> str: + try: + return platform.python_implementation() + except Exception: + return "unknown" + + +def get_python_version() -> str: + try: + return platform.python_version() + except Exception: + return "unknown" + + +def get_architecture() -> Arch: + try: + machine = platform.machine().lower() + except Exception: + return "unknown" + + if machine in ("arm64", "aarch64"): + return "arm64" + + # TODO: untested + if machine == "arm": + return "arm" + + if machine == "x86_64": + return "x64" + + # TODO: untested + if sys.maxsize <= 2**32: + return "x32" + + if machine: + return OtherArch(machine) + + return "unknown" + + +def _merge_mappings( + obj1: Mapping[_T_co, Union[_T, Omit]], + obj2: Mapping[_T_co, Union[_T, Omit]], +) -> Dict[_T_co, _T]: + """Merge two mappings of the same type, removing any values that are instances of `Omit`. + + In cases with duplicate keys the second mapping takes precedence. + """ + merged = {**obj1, **obj2} + return {key: value for key, value in merged.items() if not isinstance(value, Omit)} diff --git a/src/courier/_client.py b/src/courier/_client.py new file mode 100644 index 00000000..f548a44a --- /dev/null +++ b/src/courier/_client.py @@ -0,0 +1,1559 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, Any, Mapping +from typing_extensions import Self, override + +import httpx + +from . import _exceptions +from ._qs import Querystring +from ._types import ( + Omit, + Timeout, + NotGiven, + Transport, + ProxiesTypes, + RequestOptions, + not_given, +) +from ._utils import ( + is_given, + is_mapping_t, + get_async_library, +) +from ._compat import cached_property +from ._version import __version__ +from ._streaming import Stream as Stream, AsyncStream as AsyncStream +from ._exceptions import CourierError, APIStatusError +from ._base_client import ( + DEFAULT_MAX_RETRIES, + SyncAPIClient, + AsyncAPIClient, +) + +if TYPE_CHECKING: + from .resources import ( + auth, + send, + lists, + users, + brands, + digests, + inbound, + tenants, + journeys, + messages, + profiles, + requests, + audiences, + providers, + broadcasts, + automations, + audit_events, + translations, + notifications, + routing_strategies, + workspace_preferences, + ) + from .resources.auth import AuthResource, AsyncAuthResource + from .resources.send import SendResource, AsyncSendResource + from .resources.brands import BrandsResource, AsyncBrandsResource + from .resources.inbound import InboundResource, AsyncInboundResource + from .resources.messages import MessagesResource, AsyncMessagesResource + from .resources.requests import RequestsResource, AsyncRequestsResource + from .resources.audiences import AudiencesResource, AsyncAudiencesResource + from .resources.broadcasts import BroadcastsResource, AsyncBroadcastsResource + from .resources.lists.lists import ListsResource, AsyncListsResource + from .resources.users.users import UsersResource, AsyncUsersResource + from .resources.audit_events import AuditEventsResource, AsyncAuditEventsResource + from .resources.translations import TranslationsResource, AsyncTranslationsResource + from .resources.digests.digests import DigestsResource, AsyncDigestsResource + from .resources.tenants.tenants import TenantsResource, AsyncTenantsResource + from .resources.journeys.journeys import JourneysResource, AsyncJourneysResource + from .resources.profiles.profiles import ProfilesResource, AsyncProfilesResource + from .resources.routing_strategies import RoutingStrategiesResource, AsyncRoutingStrategiesResource + from .resources.providers.providers import ProvidersResource, AsyncProvidersResource + from .resources.automations.automations import AutomationsResource, AsyncAutomationsResource + from .resources.notifications.notifications import NotificationsResource, AsyncNotificationsResource + from .resources.workspace_preferences.workspace_preferences import ( + WorkspacePreferencesResource, + AsyncWorkspacePreferencesResource, + ) + +__all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "Courier", "AsyncCourier", "Client", "AsyncClient"] + + +class Courier(SyncAPIClient): + # client options + api_key: str + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. + # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.Client | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new synchronous Courier client instance. + + This automatically infers the `api_key` argument from the `COURIER_API_KEY` environment variable if it is not provided. + """ + if api_key is None: + api_key = os.environ.get("COURIER_API_KEY") + if api_key is None: + raise CourierError( + "The api_key client option must be set either by passing api_key to the client or by setting the COURIER_API_KEY environment variable" + ) + self.api_key = api_key + + if base_url is None: + base_url = os.environ.get("COURIER_BASE_URL") + if base_url is None: + base_url = f"https://api.courier.com" + + custom_headers_env = os.environ.get("COURIER_CUSTOM_HEADERS") + if custom_headers_env is not None: + parsed: dict[str, str] = {} + for line in custom_headers_env.split("\n"): + colon = line.find(":") + if colon >= 0: + parsed[line[:colon].strip()] = line[colon + 1 :].strip() + default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})} + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + @cached_property + def send(self) -> SendResource: + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + from .resources.send import SendResource + + return SendResource(self) + + @cached_property + def audiences(self) -> AudiencesResource: + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + from .resources.audiences import AudiencesResource + + return AudiencesResource(self) + + @cached_property + def providers(self) -> ProvidersResource: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + from .resources.providers import ProvidersResource + + return ProvidersResource(self) + + @cached_property + def audit_events(self) -> AuditEventsResource: + """Read the audit trail of configuration and access changes in your workspace.""" + from .resources.audit_events import AuditEventsResource + + return AuditEventsResource(self) + + @cached_property + def auth(self) -> AuthResource: + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + from .resources.auth import AuthResource + + return AuthResource(self) + + @cached_property + def automations(self) -> AutomationsResource: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + from .resources.automations import AutomationsResource + + return AutomationsResource(self) + + @cached_property + def journeys(self) -> JourneysResource: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + from .resources.journeys import JourneysResource + + return JourneysResource(self) + + @cached_property + def broadcasts(self) -> BroadcastsResource: + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + from .resources.broadcasts import BroadcastsResource + + return BroadcastsResource(self) + + @cached_property + def brands(self) -> BrandsResource: + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + from .resources.brands import BrandsResource + + return BrandsResource(self) + + @cached_property + def digests(self) -> DigestsResource: + from .resources.digests import DigestsResource + + return DigestsResource(self) + + @cached_property + def inbound(self) -> InboundResource: + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + from .resources.inbound import InboundResource + + return InboundResource(self) + + @cached_property + def lists(self) -> ListsResource: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + from .resources.lists import ListsResource + + return ListsResource(self) + + @cached_property + def messages(self) -> MessagesResource: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.messages import MessagesResource + + return MessagesResource(self) + + @cached_property + def requests(self) -> RequestsResource: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.requests import RequestsResource + + return RequestsResource(self) + + @cached_property + def notifications(self) -> NotificationsResource: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + from .resources.notifications import NotificationsResource + + return NotificationsResource(self) + + @cached_property + def routing_strategies(self) -> RoutingStrategiesResource: + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + from .resources.routing_strategies import RoutingStrategiesResource + + return RoutingStrategiesResource(self) + + @cached_property + def workspace_preferences(self) -> WorkspacePreferencesResource: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + from .resources.workspace_preferences import WorkspacePreferencesResource + + return WorkspacePreferencesResource(self) + + @cached_property + def profiles(self) -> ProfilesResource: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + from .resources.profiles import ProfilesResource + + return ProfilesResource(self) + + @cached_property + def tenants(self) -> TenantsResource: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + from .resources.tenants import TenantsResource + + return TenantsResource(self) + + @cached_property + def translations(self) -> TranslationsResource: + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + from .resources.translations import TranslationsResource + + return TranslationsResource(self) + + @cached_property + def users(self) -> UsersResource: + from .resources.users import UsersResource + + return UsersResource(self) + + @cached_property + def with_raw_response(self) -> CourierWithRawResponse: + return CourierWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> CourierWithStreamedResponse: + return CourierWithStreamedResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + api_key = self.api_key + return {"Authorization": f"Bearer {api_key}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "X-Stainless-Async": "false", + **self._custom_headers, + } + + def copy( + self, + *, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = not_given, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AsyncCourier(AsyncAPIClient): + # client options + api_key: str + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. + # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details. + http_client: httpx.AsyncClient | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new async AsyncCourier client instance. + + This automatically infers the `api_key` argument from the `COURIER_API_KEY` environment variable if it is not provided. + """ + if api_key is None: + api_key = os.environ.get("COURIER_API_KEY") + if api_key is None: + raise CourierError( + "The api_key client option must be set either by passing api_key to the client or by setting the COURIER_API_KEY environment variable" + ) + self.api_key = api_key + + if base_url is None: + base_url = os.environ.get("COURIER_BASE_URL") + if base_url is None: + base_url = f"https://api.courier.com" + + custom_headers_env = os.environ.get("COURIER_CUSTOM_HEADERS") + if custom_headers_env is not None: + parsed: dict[str, str] = {} + for line in custom_headers_env.split("\n"): + colon = line.find(":") + if colon >= 0: + parsed[line[:colon].strip()] = line[colon + 1 :].strip() + default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})} + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + @cached_property + def send(self) -> AsyncSendResource: + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + from .resources.send import AsyncSendResource + + return AsyncSendResource(self) + + @cached_property + def audiences(self) -> AsyncAudiencesResource: + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + from .resources.audiences import AsyncAudiencesResource + + return AsyncAudiencesResource(self) + + @cached_property + def providers(self) -> AsyncProvidersResource: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + from .resources.providers import AsyncProvidersResource + + return AsyncProvidersResource(self) + + @cached_property + def audit_events(self) -> AsyncAuditEventsResource: + """Read the audit trail of configuration and access changes in your workspace.""" + from .resources.audit_events import AsyncAuditEventsResource + + return AsyncAuditEventsResource(self) + + @cached_property + def auth(self) -> AsyncAuthResource: + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + from .resources.auth import AsyncAuthResource + + return AsyncAuthResource(self) + + @cached_property + def automations(self) -> AsyncAutomationsResource: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + from .resources.automations import AsyncAutomationsResource + + return AsyncAutomationsResource(self) + + @cached_property + def journeys(self) -> AsyncJourneysResource: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + from .resources.journeys import AsyncJourneysResource + + return AsyncJourneysResource(self) + + @cached_property + def broadcasts(self) -> AsyncBroadcastsResource: + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + from .resources.broadcasts import AsyncBroadcastsResource + + return AsyncBroadcastsResource(self) + + @cached_property + def brands(self) -> AsyncBrandsResource: + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + from .resources.brands import AsyncBrandsResource + + return AsyncBrandsResource(self) + + @cached_property + def digests(self) -> AsyncDigestsResource: + from .resources.digests import AsyncDigestsResource + + return AsyncDigestsResource(self) + + @cached_property + def inbound(self) -> AsyncInboundResource: + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + from .resources.inbound import AsyncInboundResource + + return AsyncInboundResource(self) + + @cached_property + def lists(self) -> AsyncListsResource: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + from .resources.lists import AsyncListsResource + + return AsyncListsResource(self) + + @cached_property + def messages(self) -> AsyncMessagesResource: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.messages import AsyncMessagesResource + + return AsyncMessagesResource(self) + + @cached_property + def requests(self) -> AsyncRequestsResource: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.requests import AsyncRequestsResource + + return AsyncRequestsResource(self) + + @cached_property + def notifications(self) -> AsyncNotificationsResource: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + from .resources.notifications import AsyncNotificationsResource + + return AsyncNotificationsResource(self) + + @cached_property + def routing_strategies(self) -> AsyncRoutingStrategiesResource: + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + from .resources.routing_strategies import AsyncRoutingStrategiesResource + + return AsyncRoutingStrategiesResource(self) + + @cached_property + def workspace_preferences(self) -> AsyncWorkspacePreferencesResource: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + from .resources.workspace_preferences import AsyncWorkspacePreferencesResource + + return AsyncWorkspacePreferencesResource(self) + + @cached_property + def profiles(self) -> AsyncProfilesResource: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + from .resources.profiles import AsyncProfilesResource + + return AsyncProfilesResource(self) + + @cached_property + def tenants(self) -> AsyncTenantsResource: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + from .resources.tenants import AsyncTenantsResource + + return AsyncTenantsResource(self) + + @cached_property + def translations(self) -> AsyncTranslationsResource: + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + from .resources.translations import AsyncTranslationsResource + + return AsyncTranslationsResource(self) + + @cached_property + def users(self) -> AsyncUsersResource: + from .resources.users import AsyncUsersResource + + return AsyncUsersResource(self) + + @cached_property + def with_raw_response(self) -> AsyncCourierWithRawResponse: + return AsyncCourierWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncCourierWithStreamedResponse: + return AsyncCourierWithStreamedResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + api_key = self.api_key + return {"Authorization": f"Bearer {api_key}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "X-Stainless-Async": f"async:{get_async_library()}", + **self._custom_headers, + } + + def copy( + self, + *, + api_key: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = not_given, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = not_given, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + base_url=base_url or self.base_url, + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + **_extra_kwargs, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class CourierWithRawResponse: + _client: Courier + + def __init__(self, client: Courier) -> None: + self._client = client + + @cached_property + def send(self) -> send.SendResourceWithRawResponse: + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + from .resources.send import SendResourceWithRawResponse + + return SendResourceWithRawResponse(self._client.send) + + @cached_property + def audiences(self) -> audiences.AudiencesResourceWithRawResponse: + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + from .resources.audiences import AudiencesResourceWithRawResponse + + return AudiencesResourceWithRawResponse(self._client.audiences) + + @cached_property + def providers(self) -> providers.ProvidersResourceWithRawResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + from .resources.providers import ProvidersResourceWithRawResponse + + return ProvidersResourceWithRawResponse(self._client.providers) + + @cached_property + def audit_events(self) -> audit_events.AuditEventsResourceWithRawResponse: + """Read the audit trail of configuration and access changes in your workspace.""" + from .resources.audit_events import AuditEventsResourceWithRawResponse + + return AuditEventsResourceWithRawResponse(self._client.audit_events) + + @cached_property + def auth(self) -> auth.AuthResourceWithRawResponse: + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + from .resources.auth import AuthResourceWithRawResponse + + return AuthResourceWithRawResponse(self._client.auth) + + @cached_property + def automations(self) -> automations.AutomationsResourceWithRawResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + from .resources.automations import AutomationsResourceWithRawResponse + + return AutomationsResourceWithRawResponse(self._client.automations) + + @cached_property + def journeys(self) -> journeys.JourneysResourceWithRawResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + from .resources.journeys import JourneysResourceWithRawResponse + + return JourneysResourceWithRawResponse(self._client.journeys) + + @cached_property + def broadcasts(self) -> broadcasts.BroadcastsResourceWithRawResponse: + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + from .resources.broadcasts import BroadcastsResourceWithRawResponse + + return BroadcastsResourceWithRawResponse(self._client.broadcasts) + + @cached_property + def brands(self) -> brands.BrandsResourceWithRawResponse: + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + from .resources.brands import BrandsResourceWithRawResponse + + return BrandsResourceWithRawResponse(self._client.brands) + + @cached_property + def digests(self) -> digests.DigestsResourceWithRawResponse: + from .resources.digests import DigestsResourceWithRawResponse + + return DigestsResourceWithRawResponse(self._client.digests) + + @cached_property + def inbound(self) -> inbound.InboundResourceWithRawResponse: + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + from .resources.inbound import InboundResourceWithRawResponse + + return InboundResourceWithRawResponse(self._client.inbound) + + @cached_property + def lists(self) -> lists.ListsResourceWithRawResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + from .resources.lists import ListsResourceWithRawResponse + + return ListsResourceWithRawResponse(self._client.lists) + + @cached_property + def messages(self) -> messages.MessagesResourceWithRawResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.messages import MessagesResourceWithRawResponse + + return MessagesResourceWithRawResponse(self._client.messages) + + @cached_property + def requests(self) -> requests.RequestsResourceWithRawResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.requests import RequestsResourceWithRawResponse + + return RequestsResourceWithRawResponse(self._client.requests) + + @cached_property + def notifications(self) -> notifications.NotificationsResourceWithRawResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + from .resources.notifications import NotificationsResourceWithRawResponse + + return NotificationsResourceWithRawResponse(self._client.notifications) + + @cached_property + def routing_strategies(self) -> routing_strategies.RoutingStrategiesResourceWithRawResponse: + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + from .resources.routing_strategies import RoutingStrategiesResourceWithRawResponse + + return RoutingStrategiesResourceWithRawResponse(self._client.routing_strategies) + + @cached_property + def workspace_preferences(self) -> workspace_preferences.WorkspacePreferencesResourceWithRawResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + from .resources.workspace_preferences import WorkspacePreferencesResourceWithRawResponse + + return WorkspacePreferencesResourceWithRawResponse(self._client.workspace_preferences) + + @cached_property + def profiles(self) -> profiles.ProfilesResourceWithRawResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + from .resources.profiles import ProfilesResourceWithRawResponse + + return ProfilesResourceWithRawResponse(self._client.profiles) + + @cached_property + def tenants(self) -> tenants.TenantsResourceWithRawResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + from .resources.tenants import TenantsResourceWithRawResponse + + return TenantsResourceWithRawResponse(self._client.tenants) + + @cached_property + def translations(self) -> translations.TranslationsResourceWithRawResponse: + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + from .resources.translations import TranslationsResourceWithRawResponse + + return TranslationsResourceWithRawResponse(self._client.translations) + + @cached_property + def users(self) -> users.UsersResourceWithRawResponse: + from .resources.users import UsersResourceWithRawResponse + + return UsersResourceWithRawResponse(self._client.users) + + +class AsyncCourierWithRawResponse: + _client: AsyncCourier + + def __init__(self, client: AsyncCourier) -> None: + self._client = client + + @cached_property + def send(self) -> send.AsyncSendResourceWithRawResponse: + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + from .resources.send import AsyncSendResourceWithRawResponse + + return AsyncSendResourceWithRawResponse(self._client.send) + + @cached_property + def audiences(self) -> audiences.AsyncAudiencesResourceWithRawResponse: + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + from .resources.audiences import AsyncAudiencesResourceWithRawResponse + + return AsyncAudiencesResourceWithRawResponse(self._client.audiences) + + @cached_property + def providers(self) -> providers.AsyncProvidersResourceWithRawResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + from .resources.providers import AsyncProvidersResourceWithRawResponse + + return AsyncProvidersResourceWithRawResponse(self._client.providers) + + @cached_property + def audit_events(self) -> audit_events.AsyncAuditEventsResourceWithRawResponse: + """Read the audit trail of configuration and access changes in your workspace.""" + from .resources.audit_events import AsyncAuditEventsResourceWithRawResponse + + return AsyncAuditEventsResourceWithRawResponse(self._client.audit_events) + + @cached_property + def auth(self) -> auth.AsyncAuthResourceWithRawResponse: + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + from .resources.auth import AsyncAuthResourceWithRawResponse + + return AsyncAuthResourceWithRawResponse(self._client.auth) + + @cached_property + def automations(self) -> automations.AsyncAutomationsResourceWithRawResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + from .resources.automations import AsyncAutomationsResourceWithRawResponse + + return AsyncAutomationsResourceWithRawResponse(self._client.automations) + + @cached_property + def journeys(self) -> journeys.AsyncJourneysResourceWithRawResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + from .resources.journeys import AsyncJourneysResourceWithRawResponse + + return AsyncJourneysResourceWithRawResponse(self._client.journeys) + + @cached_property + def broadcasts(self) -> broadcasts.AsyncBroadcastsResourceWithRawResponse: + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + from .resources.broadcasts import AsyncBroadcastsResourceWithRawResponse + + return AsyncBroadcastsResourceWithRawResponse(self._client.broadcasts) + + @cached_property + def brands(self) -> brands.AsyncBrandsResourceWithRawResponse: + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + from .resources.brands import AsyncBrandsResourceWithRawResponse + + return AsyncBrandsResourceWithRawResponse(self._client.brands) + + @cached_property + def digests(self) -> digests.AsyncDigestsResourceWithRawResponse: + from .resources.digests import AsyncDigestsResourceWithRawResponse + + return AsyncDigestsResourceWithRawResponse(self._client.digests) + + @cached_property + def inbound(self) -> inbound.AsyncInboundResourceWithRawResponse: + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + from .resources.inbound import AsyncInboundResourceWithRawResponse + + return AsyncInboundResourceWithRawResponse(self._client.inbound) + + @cached_property + def lists(self) -> lists.AsyncListsResourceWithRawResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + from .resources.lists import AsyncListsResourceWithRawResponse + + return AsyncListsResourceWithRawResponse(self._client.lists) + + @cached_property + def messages(self) -> messages.AsyncMessagesResourceWithRawResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.messages import AsyncMessagesResourceWithRawResponse + + return AsyncMessagesResourceWithRawResponse(self._client.messages) + + @cached_property + def requests(self) -> requests.AsyncRequestsResourceWithRawResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.requests import AsyncRequestsResourceWithRawResponse + + return AsyncRequestsResourceWithRawResponse(self._client.requests) + + @cached_property + def notifications(self) -> notifications.AsyncNotificationsResourceWithRawResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + from .resources.notifications import AsyncNotificationsResourceWithRawResponse + + return AsyncNotificationsResourceWithRawResponse(self._client.notifications) + + @cached_property + def routing_strategies(self) -> routing_strategies.AsyncRoutingStrategiesResourceWithRawResponse: + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + from .resources.routing_strategies import AsyncRoutingStrategiesResourceWithRawResponse + + return AsyncRoutingStrategiesResourceWithRawResponse(self._client.routing_strategies) + + @cached_property + def workspace_preferences(self) -> workspace_preferences.AsyncWorkspacePreferencesResourceWithRawResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + from .resources.workspace_preferences import AsyncWorkspacePreferencesResourceWithRawResponse + + return AsyncWorkspacePreferencesResourceWithRawResponse(self._client.workspace_preferences) + + @cached_property + def profiles(self) -> profiles.AsyncProfilesResourceWithRawResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + from .resources.profiles import AsyncProfilesResourceWithRawResponse + + return AsyncProfilesResourceWithRawResponse(self._client.profiles) + + @cached_property + def tenants(self) -> tenants.AsyncTenantsResourceWithRawResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + from .resources.tenants import AsyncTenantsResourceWithRawResponse + + return AsyncTenantsResourceWithRawResponse(self._client.tenants) + + @cached_property + def translations(self) -> translations.AsyncTranslationsResourceWithRawResponse: + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + from .resources.translations import AsyncTranslationsResourceWithRawResponse + + return AsyncTranslationsResourceWithRawResponse(self._client.translations) + + @cached_property + def users(self) -> users.AsyncUsersResourceWithRawResponse: + from .resources.users import AsyncUsersResourceWithRawResponse + + return AsyncUsersResourceWithRawResponse(self._client.users) + + +class CourierWithStreamedResponse: + _client: Courier + + def __init__(self, client: Courier) -> None: + self._client = client + + @cached_property + def send(self) -> send.SendResourceWithStreamingResponse: + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + from .resources.send import SendResourceWithStreamingResponse + + return SendResourceWithStreamingResponse(self._client.send) + + @cached_property + def audiences(self) -> audiences.AudiencesResourceWithStreamingResponse: + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + from .resources.audiences import AudiencesResourceWithStreamingResponse + + return AudiencesResourceWithStreamingResponse(self._client.audiences) + + @cached_property + def providers(self) -> providers.ProvidersResourceWithStreamingResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + from .resources.providers import ProvidersResourceWithStreamingResponse + + return ProvidersResourceWithStreamingResponse(self._client.providers) + + @cached_property + def audit_events(self) -> audit_events.AuditEventsResourceWithStreamingResponse: + """Read the audit trail of configuration and access changes in your workspace.""" + from .resources.audit_events import AuditEventsResourceWithStreamingResponse + + return AuditEventsResourceWithStreamingResponse(self._client.audit_events) + + @cached_property + def auth(self) -> auth.AuthResourceWithStreamingResponse: + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + from .resources.auth import AuthResourceWithStreamingResponse + + return AuthResourceWithStreamingResponse(self._client.auth) + + @cached_property + def automations(self) -> automations.AutomationsResourceWithStreamingResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + from .resources.automations import AutomationsResourceWithStreamingResponse + + return AutomationsResourceWithStreamingResponse(self._client.automations) + + @cached_property + def journeys(self) -> journeys.JourneysResourceWithStreamingResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + from .resources.journeys import JourneysResourceWithStreamingResponse + + return JourneysResourceWithStreamingResponse(self._client.journeys) + + @cached_property + def broadcasts(self) -> broadcasts.BroadcastsResourceWithStreamingResponse: + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + from .resources.broadcasts import BroadcastsResourceWithStreamingResponse + + return BroadcastsResourceWithStreamingResponse(self._client.broadcasts) + + @cached_property + def brands(self) -> brands.BrandsResourceWithStreamingResponse: + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + from .resources.brands import BrandsResourceWithStreamingResponse + + return BrandsResourceWithStreamingResponse(self._client.brands) + + @cached_property + def digests(self) -> digests.DigestsResourceWithStreamingResponse: + from .resources.digests import DigestsResourceWithStreamingResponse + + return DigestsResourceWithStreamingResponse(self._client.digests) + + @cached_property + def inbound(self) -> inbound.InboundResourceWithStreamingResponse: + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + from .resources.inbound import InboundResourceWithStreamingResponse + + return InboundResourceWithStreamingResponse(self._client.inbound) + + @cached_property + def lists(self) -> lists.ListsResourceWithStreamingResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + from .resources.lists import ListsResourceWithStreamingResponse + + return ListsResourceWithStreamingResponse(self._client.lists) + + @cached_property + def messages(self) -> messages.MessagesResourceWithStreamingResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.messages import MessagesResourceWithStreamingResponse + + return MessagesResourceWithStreamingResponse(self._client.messages) + + @cached_property + def requests(self) -> requests.RequestsResourceWithStreamingResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.requests import RequestsResourceWithStreamingResponse + + return RequestsResourceWithStreamingResponse(self._client.requests) + + @cached_property + def notifications(self) -> notifications.NotificationsResourceWithStreamingResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + from .resources.notifications import NotificationsResourceWithStreamingResponse + + return NotificationsResourceWithStreamingResponse(self._client.notifications) + + @cached_property + def routing_strategies(self) -> routing_strategies.RoutingStrategiesResourceWithStreamingResponse: + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + from .resources.routing_strategies import RoutingStrategiesResourceWithStreamingResponse + + return RoutingStrategiesResourceWithStreamingResponse(self._client.routing_strategies) + + @cached_property + def workspace_preferences(self) -> workspace_preferences.WorkspacePreferencesResourceWithStreamingResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + from .resources.workspace_preferences import WorkspacePreferencesResourceWithStreamingResponse + + return WorkspacePreferencesResourceWithStreamingResponse(self._client.workspace_preferences) + + @cached_property + def profiles(self) -> profiles.ProfilesResourceWithStreamingResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + from .resources.profiles import ProfilesResourceWithStreamingResponse + + return ProfilesResourceWithStreamingResponse(self._client.profiles) + + @cached_property + def tenants(self) -> tenants.TenantsResourceWithStreamingResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + from .resources.tenants import TenantsResourceWithStreamingResponse + + return TenantsResourceWithStreamingResponse(self._client.tenants) + + @cached_property + def translations(self) -> translations.TranslationsResourceWithStreamingResponse: + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + from .resources.translations import TranslationsResourceWithStreamingResponse + + return TranslationsResourceWithStreamingResponse(self._client.translations) + + @cached_property + def users(self) -> users.UsersResourceWithStreamingResponse: + from .resources.users import UsersResourceWithStreamingResponse + + return UsersResourceWithStreamingResponse(self._client.users) + + +class AsyncCourierWithStreamedResponse: + _client: AsyncCourier + + def __init__(self, client: AsyncCourier) -> None: + self._client = client + + @cached_property + def send(self) -> send.AsyncSendResourceWithStreamingResponse: + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + from .resources.send import AsyncSendResourceWithStreamingResponse + + return AsyncSendResourceWithStreamingResponse(self._client.send) + + @cached_property + def audiences(self) -> audiences.AsyncAudiencesResourceWithStreamingResponse: + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + from .resources.audiences import AsyncAudiencesResourceWithStreamingResponse + + return AsyncAudiencesResourceWithStreamingResponse(self._client.audiences) + + @cached_property + def providers(self) -> providers.AsyncProvidersResourceWithStreamingResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + from .resources.providers import AsyncProvidersResourceWithStreamingResponse + + return AsyncProvidersResourceWithStreamingResponse(self._client.providers) + + @cached_property + def audit_events(self) -> audit_events.AsyncAuditEventsResourceWithStreamingResponse: + """Read the audit trail of configuration and access changes in your workspace.""" + from .resources.audit_events import AsyncAuditEventsResourceWithStreamingResponse + + return AsyncAuditEventsResourceWithStreamingResponse(self._client.audit_events) + + @cached_property + def auth(self) -> auth.AsyncAuthResourceWithStreamingResponse: + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + from .resources.auth import AsyncAuthResourceWithStreamingResponse + + return AsyncAuthResourceWithStreamingResponse(self._client.auth) + + @cached_property + def automations(self) -> automations.AsyncAutomationsResourceWithStreamingResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + from .resources.automations import AsyncAutomationsResourceWithStreamingResponse + + return AsyncAutomationsResourceWithStreamingResponse(self._client.automations) + + @cached_property + def journeys(self) -> journeys.AsyncJourneysResourceWithStreamingResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + from .resources.journeys import AsyncJourneysResourceWithStreamingResponse + + return AsyncJourneysResourceWithStreamingResponse(self._client.journeys) + + @cached_property + def broadcasts(self) -> broadcasts.AsyncBroadcastsResourceWithStreamingResponse: + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + from .resources.broadcasts import AsyncBroadcastsResourceWithStreamingResponse + + return AsyncBroadcastsResourceWithStreamingResponse(self._client.broadcasts) + + @cached_property + def brands(self) -> brands.AsyncBrandsResourceWithStreamingResponse: + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + from .resources.brands import AsyncBrandsResourceWithStreamingResponse + + return AsyncBrandsResourceWithStreamingResponse(self._client.brands) + + @cached_property + def digests(self) -> digests.AsyncDigestsResourceWithStreamingResponse: + from .resources.digests import AsyncDigestsResourceWithStreamingResponse + + return AsyncDigestsResourceWithStreamingResponse(self._client.digests) + + @cached_property + def inbound(self) -> inbound.AsyncInboundResourceWithStreamingResponse: + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + from .resources.inbound import AsyncInboundResourceWithStreamingResponse + + return AsyncInboundResourceWithStreamingResponse(self._client.inbound) + + @cached_property + def lists(self) -> lists.AsyncListsResourceWithStreamingResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + from .resources.lists import AsyncListsResourceWithStreamingResponse + + return AsyncListsResourceWithStreamingResponse(self._client.lists) + + @cached_property + def messages(self) -> messages.AsyncMessagesResourceWithStreamingResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.messages import AsyncMessagesResourceWithStreamingResponse + + return AsyncMessagesResourceWithStreamingResponse(self._client.messages) + + @cached_property + def requests(self) -> requests.AsyncRequestsResourceWithStreamingResponse: + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + from .resources.requests import AsyncRequestsResourceWithStreamingResponse + + return AsyncRequestsResourceWithStreamingResponse(self._client.requests) + + @cached_property + def notifications(self) -> notifications.AsyncNotificationsResourceWithStreamingResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + from .resources.notifications import AsyncNotificationsResourceWithStreamingResponse + + return AsyncNotificationsResourceWithStreamingResponse(self._client.notifications) + + @cached_property + def routing_strategies(self) -> routing_strategies.AsyncRoutingStrategiesResourceWithStreamingResponse: + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + from .resources.routing_strategies import AsyncRoutingStrategiesResourceWithStreamingResponse + + return AsyncRoutingStrategiesResourceWithStreamingResponse(self._client.routing_strategies) + + @cached_property + def workspace_preferences(self) -> workspace_preferences.AsyncWorkspacePreferencesResourceWithStreamingResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + from .resources.workspace_preferences import AsyncWorkspacePreferencesResourceWithStreamingResponse + + return AsyncWorkspacePreferencesResourceWithStreamingResponse(self._client.workspace_preferences) + + @cached_property + def profiles(self) -> profiles.AsyncProfilesResourceWithStreamingResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + from .resources.profiles import AsyncProfilesResourceWithStreamingResponse + + return AsyncProfilesResourceWithStreamingResponse(self._client.profiles) + + @cached_property + def tenants(self) -> tenants.AsyncTenantsResourceWithStreamingResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + from .resources.tenants import AsyncTenantsResourceWithStreamingResponse + + return AsyncTenantsResourceWithStreamingResponse(self._client.tenants) + + @cached_property + def translations(self) -> translations.AsyncTranslationsResourceWithStreamingResponse: + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + from .resources.translations import AsyncTranslationsResourceWithStreamingResponse + + return AsyncTranslationsResourceWithStreamingResponse(self._client.translations) + + @cached_property + def users(self) -> users.AsyncUsersResourceWithStreamingResponse: + from .resources.users import AsyncUsersResourceWithStreamingResponse + + return AsyncUsersResourceWithStreamingResponse(self._client.users) + + +Client = Courier + +AsyncClient = AsyncCourier diff --git a/src/courier/_compat.py b/src/courier/_compat.py new file mode 100644 index 00000000..e6690a4f --- /dev/null +++ b/src/courier/_compat.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload +from datetime import date, datetime +from typing_extensions import Self, Literal, TypedDict + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import IncEx, StrBytesIntFloat + +_T = TypeVar("_T") +_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) + +# --------------- Pydantic v2, v3 compatibility --------------- + +# Pyright incorrectly reports some of our functions as overriding a method when they don't +# pyright: reportIncompatibleMethodOverride=false + +PYDANTIC_V1 = pydantic.VERSION.startswith("1.") + +if TYPE_CHECKING: + + def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001 + ... + + def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001 + ... + + def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001 + ... + + def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001 + ... + + def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001 + ... + + def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001 + ... + + def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 + ... + +else: + # v1 re-exports + if PYDANTIC_V1: + from pydantic.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime + else: + from ._utils import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + parse_date as parse_date, + is_typeddict as is_typeddict, + parse_datetime as parse_datetime, + is_literal_type as is_literal_type, + ) + + +# refactored config +if TYPE_CHECKING: + from pydantic import ConfigDict as ConfigDict +else: + if PYDANTIC_V1: + # TODO: provide an error message here? + ConfigDict = None + else: + from pydantic import ConfigDict as ConfigDict + + +# renamed methods / properties +def parse_obj(model: type[_ModelT], value: object) -> _ModelT: + if PYDANTIC_V1: + return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + else: + return model.model_validate(value) + + +def field_is_required(field: FieldInfo) -> bool: + if PYDANTIC_V1: + return field.required # type: ignore + return field.is_required() + + +def field_get_default(field: FieldInfo) -> Any: + value = field.get_default() + if PYDANTIC_V1: + return value + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None + return value + + +def field_outer_type(field: FieldInfo) -> Any: + if PYDANTIC_V1: + return field.outer_type_ # type: ignore + return field.annotation + + +def get_model_config(model: type[pydantic.BaseModel]) -> Any: + if PYDANTIC_V1: + return model.__config__ # type: ignore + return model.model_config + + +def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]: + if PYDANTIC_V1: + return model.__fields__ # type: ignore + return model.model_fields + + +def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT: + if PYDANTIC_V1: + return model.copy(deep=deep) # type: ignore + return model.model_copy(deep=deep) + + +def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: + if PYDANTIC_V1: + return model.json(indent=indent) # type: ignore + return model.model_dump_json(indent=indent) + + +class _ModelDumpKwargs(TypedDict, total=False): + by_alias: bool + + +def model_dump( + model: pydantic.BaseModel, + *, + exclude: IncEx | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + warnings: bool = True, + mode: Literal["json", "python"] = "python", + 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, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + # warnings are not supported in Pydantic v1 + warnings=True if PYDANTIC_V1 else warnings, + **kwargs, + ) + return cast( + "dict[str, Any]", + model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias) + ), + ) + + +def model_parse(model: type[_ModelT], data: Any) -> _ModelT: + if PYDANTIC_V1: + return model.parse_obj(data) # pyright: ignore[reportDeprecated] + return model.model_validate(data) + + +# generic models +if TYPE_CHECKING: + + class GenericModel(pydantic.BaseModel): ... + +else: + if PYDANTIC_V1: + import pydantic.generics + + class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... + else: + # there no longer needs to be a distinction in v2 but + # we still have to create our own subclass to avoid + # inconsistent MRO ordering errors + class GenericModel(pydantic.BaseModel): ... + + +# cached properties +if TYPE_CHECKING: + cached_property = property + + # we define a separate type (copied from typeshed) + # that represents that `cached_property` is `set`able + # at runtime, which differs from `@property`. + # + # this is a separate type as editors likely special case + # `@property` and we don't want to cause issues just to have + # more helpful internal types. + + class typed_cached_property(Generic[_T]): + func: Callable[[Any], _T] + attrname: str | None + + def __init__(self, func: Callable[[Any], _T]) -> None: ... + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... + + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... + + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self: + raise NotImplementedError() + + def __set_name__(self, owner: type[Any], name: str) -> None: ... + + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T) -> None: ... +else: + from functools import cached_property as cached_property + + typed_cached_property = cached_property diff --git a/src/courier/_constants.py b/src/courier/_constants.py new file mode 100644 index 00000000..6ddf2c71 --- /dev/null +++ b/src/courier/_constants.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import httpx + +RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response" +OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to" + +# default timeout is 1 minute +DEFAULT_TIMEOUT = httpx.Timeout(timeout=60, connect=5.0) +DEFAULT_MAX_RETRIES = 2 +DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) + +INITIAL_RETRY_DELAY = 0.5 +MAX_RETRY_DELAY = 8.0 diff --git a/src/courier/_exceptions.py b/src/courier/_exceptions.py new file mode 100644 index 00000000..007b96a1 --- /dev/null +++ b/src/courier/_exceptions.py @@ -0,0 +1,108 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +__all__ = [ + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", +] + + +class CourierError(Exception): + pass + + +class APIError(CourierError): + message: str + request: httpx.Request + + body: object | None + """The API response body. + + If the API responded with a valid JSON structure then this property will be the + decoded result. + + If it isn't a valid JSON structure then this will be the raw response. + + If there was no response associated with this error then it will be `None`. + """ + + def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: # noqa: ARG002 + super().__init__(message) + self.request = request + self.message = message + self.body = body + + +class APIResponseValidationError(APIError): + response: httpx.Response + status_code: int + + def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None: + super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIStatusError(APIError): + """Raised when an API response has a status code of 4xx or 5xx.""" + + response: httpx.Response + status_code: int + + def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None: + super().__init__(message, response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIConnectionError(APIError): + def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None: + super().__init__(message, request, body=None) + + +class APITimeoutError(APIConnectionError): + def __init__(self, request: httpx.Request) -> None: + super().__init__(message="Request timed out.", request=request) + + +class BadRequestError(APIStatusError): + status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride] + + +class AuthenticationError(APIStatusError): + status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride] + + +class PermissionDeniedError(APIStatusError): + status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride] + + +class NotFoundError(APIStatusError): + status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride] + + +class ConflictError(APIStatusError): + status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride] + + +class UnprocessableEntityError(APIStatusError): + status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride] + + +class RateLimitError(APIStatusError): + status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride] + + +class InternalServerError(APIStatusError): + pass diff --git a/src/courier/_files.py b/src/courier/_files.py new file mode 100644 index 00000000..76da9e08 --- /dev/null +++ b/src/courier/_files.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import io +import os +import pathlib +from typing import Sequence, cast, overload +from typing_extensions import TypeVar, TypeGuard + +import anyio + +from ._types import ( + FileTypes, + FileContent, + RequestFiles, + HttpxFileTypes, + Base64FileInput, + HttpxFileContent, + HttpxRequestFiles, +) +from ._utils import is_list, is_mapping, is_tuple_t, is_mapping_t, is_sequence_t + +_T = TypeVar("_T") + + +def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]: + return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + + +def is_file_content(obj: object) -> TypeGuard[FileContent]: + return ( + isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + ) + + +def assert_is_file_content(obj: object, *, key: str | None = None) -> None: + if not is_file_content(obj): + prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`" + raise RuntimeError( + f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead." + ) from None + + +@overload +def to_httpx_files(files: None) -> None: ... + + +@overload +def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... + + +def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: _transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, _transform_file(file)) for key, file in files] + else: + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +def _transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = pathlib.Path(file) + return (path.name, path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +def read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return pathlib.Path(file).read_bytes() + return file + + +@overload +async def async_to_httpx_files(files: None) -> None: ... + + +@overload +async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... + + +async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: await _async_transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, await _async_transform_file(file)) for key, file in files] + else: + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +async def _async_transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = anyio.Path(file) + return (path.name, await path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], await async_read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +async def async_read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return await anyio.Path(file).read_bytes() + + return file + + +def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T: + """Copy only the containers along the given paths. + + Used to guard against mutation by extract_files without copying the entire structure. + Only dicts and lists that lie on a path are copied; everything else + is returned by reference. + + For example, given paths=[["foo", "files", "file"]] and the structure: + { + "foo": { + "bar": {"baz": {}}, + "files": {"file": } + } + } + The root dict, "foo", and "files" are copied (they lie on the path). + "bar" and "baz" are returned by reference (off the path). + """ + return _deepcopy_with_paths(item, paths, 0) + + +def _deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]], index: int) -> _T: + if not paths: + return item + if is_mapping(item): + key_to_paths: dict[str, list[Sequence[str]]] = {} + for path in paths: + if index < len(path): + key_to_paths.setdefault(path[index], []).append(path) + + # if no path continues through this mapping, it won't be mutated and copying it is redundant + if not key_to_paths: + return item + + result = dict(item) + for key, subpaths in key_to_paths.items(): + if key in result: + result[key] = _deepcopy_with_paths(result[key], subpaths, index + 1) + return cast(_T, result) + if is_list(item): + array_paths = [path for path in paths if index < len(path) and path[index] == ""] + + # if no path expects a list here, nothing will be mutated inside it - return by reference + if not array_paths: + return cast(_T, item) + return cast(_T, [_deepcopy_with_paths(entry, array_paths, index + 1) for entry in item]) + return item diff --git a/src/courier/_models.py b/src/courier/_models.py new file mode 100644 index 00000000..8c5ab260 --- /dev/null +++ b/src/courier/_models.py @@ -0,0 +1,952 @@ +from __future__ import annotations + +import os +import inspect +import weakref +from typing import ( + IO, + TYPE_CHECKING, + Any, + Type, + Union, + Generic, + TypeVar, + Callable, + Iterable, + Optional, + AsyncIterable, + cast, +) +from datetime import date, datetime +from typing_extensions import ( + List, + Unpack, + Literal, + ClassVar, + Protocol, + Required, + Annotated, + ParamSpec, + TypeAlias, + TypedDict, + TypeGuard, + final, + override, + runtime_checkable, +) + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import ( + Body, + IncEx, + Query, + ModelT, + Headers, + Timeout, + NotGiven, + AnyMapping, + HttpxRequestFiles, +) +from ._utils import ( + PropertyInfo, + is_list, + is_given, + json_safe, + lru_cache, + is_mapping, + parse_date, + coerce_boolean, + parse_datetime, + strip_not_given, + extract_type_arg, + is_annotated_type, + is_type_alias_type, + strip_annotated_type, +) +from ._compat import ( + PYDANTIC_V1, + ConfigDict, + GenericModel as BaseGenericModel, + get_args, + is_union, + parse_obj, + get_origin, + is_literal_type, + get_model_config, + get_model_fields, + field_get_default, +) +from ._constants import RAW_RESPONSE_HEADER + +if TYPE_CHECKING: + from pydantic import GetCoreSchemaHandler, ValidatorFunctionWrapHandler + from pydantic_core import CoreSchema, core_schema + from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema +else: + try: + from pydantic_core import CoreSchema, core_schema + except ImportError: + CoreSchema = None + core_schema = None + +__all__ = ["BaseModel", "GenericModel"] + +_T = TypeVar("_T") +_BaseModelT = TypeVar("_BaseModelT", bound="BaseModel") + +P = ParamSpec("P") + + +@runtime_checkable +class _ConfigProtocol(Protocol): + allow_population_by_field_name: bool + + +class BaseModel(pydantic.BaseModel): + if PYDANTIC_V1: + + @property + @override + def model_fields_set(self) -> set[str]: + # a forwards-compat shim for pydantic v2 + return self.__fields_set__ # type: ignore + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + extra: Any = pydantic.Extra.allow # type: ignore + else: + model_config: ClassVar[ConfigDict] = ConfigDict( + extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) + ) + + def to_dict( + self, + *, + mode: Literal["json", "python"] = "python", + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> dict[str, object]: + """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + mode: + If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`. + If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)` + + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value from the output. + exclude_none: Whether to exclude fields that have a value of `None` from the output. + warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2. + """ + return self.model_dump( + mode=mode, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + def to_json( + self, + *, + indent: int | None = 2, + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> str: + """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation). + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2` + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2. + """ + return self.model_dump_json( + indent=indent, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + @override + def __str__(self) -> str: + # mypy complains about an invalid self arg + return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc] + + # Override the 'construct' method in a way that supports recursive parsing without validation. + # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. + @classmethod + @override + def construct( # pyright: ignore[reportIncompatibleMethodOverride] + __cls: Type[ModelT], + _fields_set: set[str] | None = None, + **values: object, + ) -> ModelT: + m = __cls.__new__(__cls) + fields_values: dict[str, object] = {} + + config = get_model_config(__cls) + populate_by_name = ( + config.allow_population_by_field_name + if isinstance(config, _ConfigProtocol) + else config.get("populate_by_name") + ) + + if _fields_set is None: + _fields_set = set() + + model_fields = get_model_fields(__cls) + for name, field in model_fields.items(): + key = field.alias + if key is None or (key not in values and populate_by_name): + key = name + + if key in values: + fields_values[name] = _construct_field(value=values[key], field=field, key=key) + _fields_set.add(name) + else: + fields_values[name] = field_get_default(field) + + extra_field_type = _get_extra_fields_type(__cls) + + _extra = {} + for key, value in values.items(): + if key not in model_fields: + parsed = construct_type(value=value, type_=extra_field_type) if extra_field_type is not None else value + + if PYDANTIC_V1: + _fields_set.add(key) + fields_values[key] = parsed + else: + _extra[key] = parsed + + object.__setattr__(m, "__dict__", fields_values) + + if PYDANTIC_V1: + # init_private_attributes() does not exist in v2 + m._init_private_attributes() # type: ignore + + # copied from Pydantic v1's `construct()` method + object.__setattr__(m, "__fields_set__", _fields_set) + else: + # these properties are copied from Pydantic's `model_construct()` method + object.__setattr__(m, "__pydantic_private__", None) + object.__setattr__(m, "__pydantic_extra__", _extra) + object.__setattr__(m, "__pydantic_fields_set__", _fields_set) + + return m + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + # because the type signatures are technically different + # although not in practice + model_construct = construct + + if PYDANTIC_V1: + # we define aliases for some of the new pydantic v2 methods so + # that we can just document these methods without having to specify + # a specific pydantic version as some users may not know which + # pydantic version they are currently using + + @override + def model_dump( + self, + *, + mode: Literal["json", "python"] | str = "python", + include: IncEx | None = None, + exclude: IncEx | None = None, + context: Any | None = None, + by_alias: bool | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + exclude_computed_fields: bool = False, + round_trip: bool = False, + warnings: bool | Literal["none", "warn", "error"] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + ) -> dict[str, Any]: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump + + Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + Args: + mode: The mode in which `to_python` should run. + If mode is 'json', the output will only contain JSON serializable types. + If mode is 'python', the output may contain non-JSON-serializable Python objects. + include: A set of fields to include in the output. + exclude: A set of fields to exclude from the output. + context: Additional context to pass to the serializer. + by_alias: Whether to use the field's alias in the dictionary key if defined. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + exclude_computed_fields: Whether to exclude computed fields. + While this can be useful for round-tripping, it is usually recommended to use the dedicated + `round_trip` parameter instead. + round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + fallback: A function to call when an unknown value is encountered. If not provided, + a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + + Returns: + A dictionary representation of the model. + """ + if mode not in {"json", "python"}: + raise ValueError("mode must be either 'json' or 'python'") + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") + if fallback is not None: + raise ValueError("fallback is only supported in Pydantic v2") + if exclude_computed_fields != False: + raise ValueError("exclude_computed_fields is only supported in Pydantic v2") + dumped = super().dict( # pyright: ignore[reportDeprecated] + include=include, + exclude=exclude, + by_alias=by_alias if by_alias is not None else False, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + return cast("dict[str, Any]", json_safe(dumped)) if mode == "json" else dumped + + @override + def model_dump_json( + self, + *, + indent: int | None = None, + ensure_ascii: bool = False, + include: IncEx | None = None, + exclude: IncEx | None = None, + context: Any | None = None, + by_alias: bool | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + exclude_computed_fields: bool = False, + round_trip: bool = False, + warnings: bool | Literal["none", "warn", "error"] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + ) -> str: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json + + Generates a JSON representation of the model using Pydantic's `to_json` method. + + Args: + indent: Indentation to use in the JSON output. If None is passed, the output will be compact. + include: Field(s) to include in the JSON output. Can take either a string or set of strings. + exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings. + by_alias: Whether to serialize using field aliases. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to use serialization/deserialization between JSON and class instance. + warnings: Whether to show any warnings that occurred during serialization. + + Returns: + A JSON string representation of the model. + """ + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") + if fallback is not None: + raise ValueError("fallback is only supported in Pydantic v2") + if ensure_ascii != False: + raise ValueError("ensure_ascii is only supported in Pydantic v2") + if exclude_computed_fields != False: + raise ValueError("exclude_computed_fields is only supported in Pydantic v2") + return super().json( # type: ignore[reportDeprecated] + indent=indent, + include=include, + exclude=exclude, + by_alias=by_alias if by_alias is not None else False, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + +class _EagerIterable(list[_T], Generic[_T]): + """ + Accepts any Iterable[T] input (including generators), consumes it + eagerly, and validates all items upfront. + + Validation preserves the original container type where possible + (e.g. a set[T] stays a set[T]). Serialization (model_dump / JSON) + always emits a list — round-tripping through model_dump() will not + restore the original container type. + """ + + @classmethod + def __get_pydantic_core_schema__( + cls, + source_type: Any, + handler: GetCoreSchemaHandler, + ) -> CoreSchema: + (item_type,) = get_args(source_type) or (Any,) + item_schema: CoreSchema = handler.generate_schema(item_type) + list_of_items_schema: CoreSchema = core_schema.list_schema(item_schema) + + return core_schema.no_info_wrap_validator_function( + cls._validate, + list_of_items_schema, + serialization=core_schema.plain_serializer_function_ser_schema( + cls._serialize, + info_arg=False, + ), + ) + + @staticmethod + def _validate(v: Iterable[_T], handler: "ValidatorFunctionWrapHandler") -> Any: + original_type: type[Any] = type(v) + + # Normalize to list so list_schema can validate each item + if isinstance(v, list): + items: list[_T] = v + else: + try: + items = list(v) + except TypeError as e: + raise TypeError("Value is not iterable") from e + + # Validate items against the inner schema + validated: list[_T] = handler(items) + + # Reconstruct original container type + if original_type is list: + return validated + # str(list) produces the list's repr, not a string built from items, + # so skip reconstruction for str and its subclasses. + if issubclass(original_type, str): + return validated + try: + return original_type(validated) + except (TypeError, ValueError): + # If the type cannot be reconstructed, just return the validated list + return validated + + @staticmethod + def _serialize(v: Iterable[_T]) -> list[_T]: + """Always serialize as a list so Pydantic's JSON encoder is happy.""" + if isinstance(v, list): + return v + return list(v) + + +EagerIterable: TypeAlias = Annotated[Iterable[_T], _EagerIterable] + + +def _construct_field(value: object, field: FieldInfo, key: str) -> object: + if value is None: + return field_get_default(field) + + if PYDANTIC_V1: + type_ = cast(type, field.outer_type_) # type: ignore + else: + type_ = field.annotation # type: ignore + + if type_ is None: + raise RuntimeError(f"Unexpected field type is None for {key}") + + return construct_type(value=value, type_=type_, metadata=getattr(field, "metadata", None)) + + +def _get_extra_fields_type(cls: type[pydantic.BaseModel]) -> type | None: + if PYDANTIC_V1: + # TODO + return None + + schema = cls.__pydantic_core_schema__ + if schema["type"] == "model": + fields = schema["schema"] + if fields["type"] == "model-fields": + extras = fields.get("extras_schema") + if extras and "cls" in extras: + # mypy can't narrow the type + return extras["cls"] # type: ignore[no-any-return] + + return None + + +def is_basemodel(type_: type) -> bool: + """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`""" + if is_union(type_): + for variant in get_args(type_): + if is_basemodel(variant): + return True + + return False + + return is_basemodel_type(type_) + + +def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]: + origin = get_origin(type_) or type_ + if not inspect.isclass(origin): + return False + return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) + + +def build( + base_model_cls: Callable[P, _BaseModelT], + *args: P.args, + **kwargs: P.kwargs, +) -> _BaseModelT: + """Construct a BaseModel class without validation. + + This is useful for cases where you need to instantiate a `BaseModel` + from an API response as this provides type-safe params which isn't supported + by helpers like `construct_type()`. + + ```py + build(MyModel, my_field_a="foo", my_field_b=123) + ``` + """ + if args: + raise TypeError( + "Received positional arguments which are not supported; Keyword arguments must be used instead", + ) + + return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs)) + + +def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T: + """Loose coercion to the expected type with construction of nested values. + + Note: the returned value from this function is not guaranteed to match the + given type. + """ + return cast(_T, construct_type(value=value, type_=type_)) + + +def construct_type(*, value: object, type_: object, metadata: Optional[List[Any]] = None) -> object: + """Loose coercion to the expected type with construction of nested values. + + If the given value does not match the expected type then it is returned as-is. + """ + + # store a reference to the original type we were given before we extract any inner + # types so that we can properly resolve forward references in `TypeAliasType` annotations + original_type = None + + # we allow `object` as the input type because otherwise, passing things like + # `Literal['value']` will be reported as a type error by type checkers + type_ = cast("type[object]", type_) + if is_type_alias_type(type_): + original_type = type_ # type: ignore[unreachable] + type_ = type_.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if metadata is not None and len(metadata) > 0: + meta: tuple[Any, ...] = tuple(metadata) + elif is_annotated_type(type_): + meta = get_args(type_)[1:] + type_ = extract_type_arg(type_, 0) + else: + meta = tuple() + + # we need to use the origin class for any types that are subscripted generics + # e.g. Dict[str, object] + origin = get_origin(type_) or type_ + args = get_args(type_) + + if is_union(origin): + try: + return validate_type(type_=cast("type[object]", original_type or type_), value=value) + except Exception: + pass + + # if the type is a discriminated union then we want to construct the right variant + # in the union, even if the data doesn't match exactly, otherwise we'd break code + # that relies on the constructed class types, e.g. + # + # class FooType: + # kind: Literal['foo'] + # value: str + # + # class BarType: + # kind: Literal['bar'] + # value: int + # + # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then + # we'd end up constructing `FooType` when it should be `BarType`. + discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta) + if discriminator and is_mapping(value): + variant_value = value.get(discriminator.field_alias_from or discriminator.field_name) + if variant_value and isinstance(variant_value, str): + variant_type = discriminator.mapping.get(variant_value) + if variant_type: + return construct_type(type_=variant_type, value=value) + + # if the data is not valid, use the first variant that doesn't fail while deserializing + for variant in args: + try: + return construct_type(value=value, type_=variant) + except Exception: + continue + + raise RuntimeError(f"Could not convert data into a valid instance of {type_}") + + if origin == dict: + if not is_mapping(value): + return value + + _, items_type = get_args(type_) # Dict[_, items_type] + return {key: construct_type(value=item, type_=items_type) for key, item in value.items()} + + if ( + not is_literal_type(type_) + and inspect.isclass(origin) + and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)) + ): + if is_list(value): + return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value] + + if is_mapping(value): + if issubclass(type_, BaseModel): + return type_.construct(**value) # type: ignore[arg-type] + + return cast(Any, type_).construct(**value) + + if origin == list: + if not is_list(value): + return value + + inner_type = args[0] # List[inner_type] + return [construct_type(value=entry, type_=inner_type) for entry in value] + + if origin == float: + if isinstance(value, int): + coerced = float(value) + if coerced != value: + return value + return coerced + + return value + + if type_ == datetime: + try: + return parse_datetime(value) # type: ignore + except Exception: + return value + + if type_ == date: + try: + return parse_date(value) # type: ignore + except Exception: + return value + + return value + + +@runtime_checkable +class CachedDiscriminatorType(Protocol): + __discriminator__: DiscriminatorDetails + + +DISCRIMINATOR_CACHE: weakref.WeakKeyDictionary[type, DiscriminatorDetails] = weakref.WeakKeyDictionary() + + +class DiscriminatorDetails: + field_name: str + """The name of the discriminator field in the variant class, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] + ``` + + Will result in field_name='type' + """ + + field_alias_from: str | None + """The name of the discriminator field in the API response, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] = Field(alias='type_from_api') + ``` + + Will result in field_alias_from='type_from_api' + """ + + mapping: dict[str, type] + """Mapping of discriminator value to variant type, e.g. + + {'foo': FooVariant, 'bar': BarVariant} + """ + + def __init__( + self, + *, + mapping: dict[str, type], + discriminator_field: str, + discriminator_alias: str | None, + ) -> None: + self.mapping = mapping + self.field_name = discriminator_field + self.field_alias_from = discriminator_alias + + +def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None: + cached = DISCRIMINATOR_CACHE.get(union) + if cached is not None: + return cached + + discriminator_field_name: str | None = None + + for annotation in meta_annotations: + if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None: + discriminator_field_name = annotation.discriminator + break + + if not discriminator_field_name: + return None + + mapping: dict[str, type] = {} + discriminator_alias: str | None = None + + for variant in get_args(union): + variant = strip_annotated_type(variant) + if is_basemodel_type(variant): + if PYDANTIC_V1: + field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + if not field_info: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field_info.alias + + if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): + for entry in get_args(annotation): + if isinstance(entry, str): + mapping[entry] = variant + else: + field = _extract_field_schema_pv2(variant, discriminator_field_name) + if not field: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field.get("serialization_alias") + + field_schema = field["schema"] + + if field_schema["type"] == "literal": + for entry in cast("LiteralSchema", field_schema)["expected"]: + if isinstance(entry, str): + mapping[entry] = variant + + if not mapping: + return None + + details = DiscriminatorDetails( + mapping=mapping, + discriminator_field=discriminator_field_name, + discriminator_alias=discriminator_alias, + ) + DISCRIMINATOR_CACHE.setdefault(union, details) + return details + + +def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None: + schema = model.__pydantic_core_schema__ + if schema["type"] == "definitions": + schema = schema["schema"] + + if schema["type"] != "model": + return None + + schema = cast("ModelSchema", schema) + fields_schema = schema["schema"] + if fields_schema["type"] != "model-fields": + return None + + fields_schema = cast("ModelFieldsSchema", fields_schema) + field = fields_schema["fields"].get(field_name) + if not field: + return None + + return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast] + + +def validate_type(*, type_: type[_T], value: object) -> _T: + """Strict validation that the given value matches the expected type""" + if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): + return cast(_T, parse_obj(type_, value)) + + return cast(_T, _validate_non_model_type(type_=type_, value=value)) + + +def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None: + """Add a pydantic config for the given type. + + Note: this is a no-op on Pydantic v1. + """ + setattr(typ, "__pydantic_config__", config) # noqa: B010 + + +# our use of subclassing here causes weirdness for type checkers, +# so we just pretend that we don't subclass +if TYPE_CHECKING: + GenericModel = BaseModel +else: + + class GenericModel(BaseGenericModel, BaseModel): + pass + + +if not PYDANTIC_V1: + from pydantic import TypeAdapter as _TypeAdapter + + _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)) + + if TYPE_CHECKING: + from pydantic import TypeAdapter + else: + TypeAdapter = _CachedTypeAdapter + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + return TypeAdapter(type_).validate_python(value) + +elif not TYPE_CHECKING: # TODO: condition is weird + + class RootModel(GenericModel, Generic[_T]): + """Used as a placeholder to easily convert runtime types to a Pydantic format + to provide validation. + + For example: + ```py + validated = RootModel[int](__root__="5").__root__ + # validated: 5 + ``` + """ + + __root__: _T + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + model = _create_pydantic_model(type_).validate(value) + return cast(_T, model.__root__) + + def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]: + return RootModel[type_] # type: ignore + + +class FinalRequestOptionsInput(TypedDict, total=False): + method: Required[str] + url: Required[str] + params: Query + headers: Headers + max_retries: int + timeout: float | Timeout | None + files: HttpxRequestFiles | None + idempotency_key: str + content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] + json_data: Body + extra_json: AnyMapping + follow_redirects: bool + + +@final +class FinalRequestOptions(pydantic.BaseModel): + method: str + url: str + params: Query = {} + headers: Union[Headers, NotGiven] = NotGiven() + max_retries: Union[int, NotGiven] = NotGiven() + timeout: Union[float, Timeout, None, NotGiven] = NotGiven() + files: Union[HttpxRequestFiles, None] = None + idempotency_key: Union[str, None] = None + post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() + follow_redirects: Union[bool, None] = None + + content: Union[bytes, bytearray, IO[bytes], Iterable[bytes], AsyncIterable[bytes], None] = None + # It should be noted that we cannot use `json` here as that would override + # a BaseModel method in an incompatible fashion. + json_data: Union[Body, None] = None + extra_json: Union[AnyMapping, None] = None + + if PYDANTIC_V1: + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + arbitrary_types_allowed: bool = True + else: + model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) + + def get_max_retries(self, max_retries: int) -> int: + if isinstance(self.max_retries, NotGiven): + return max_retries + return self.max_retries + + def _strip_raw_response_header(self) -> None: + if not is_given(self.headers): + return + + if self.headers.get(RAW_RESPONSE_HEADER): + self.headers = {**self.headers} + self.headers.pop(RAW_RESPONSE_HEADER) + + # override the `construct` method so that we can run custom transformations. + # this is necessary as we don't want to do any actual runtime type checking + # (which means we can't use validators) but we do want to ensure that `NotGiven` + # values are not present + # + # type ignore required because we're adding explicit types to `**values` + @classmethod + def construct( # type: ignore + cls, + _fields_set: set[str] | None = None, + **values: Unpack[FinalRequestOptionsInput], + ) -> FinalRequestOptions: + kwargs: dict[str, Any] = { + # we unconditionally call `strip_not_given` on any value + # as it will just ignore any non-mapping types + key: strip_not_given(value) + for key, value in values.items() + } + if PYDANTIC_V1: + return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] + return super().model_construct(_fields_set, **kwargs) + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + model_construct = construct diff --git a/src/courier/_qs.py b/src/courier/_qs.py new file mode 100644 index 00000000..4127c19c --- /dev/null +++ b/src/courier/_qs.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +from typing import Any, List, Tuple, Union, Mapping, TypeVar +from urllib.parse import parse_qs, urlencode +from typing_extensions import get_args + +from ._types import NotGiven, ArrayFormat, NestedFormat, not_given +from ._utils import flatten + +_T = TypeVar("_T") + +PrimitiveData = Union[str, int, float, bool, None] +# this should be Data = Union[PrimitiveData, "List[Data]", "Tuple[Data]", "Mapping[str, Data]"] +# https://github.com/microsoft/pyright/issues/3555 +Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"] +Params = Mapping[str, Data] + + +class Querystring: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + *, + array_format: ArrayFormat = "repeat", + nested_format: NestedFormat = "brackets", + ) -> None: + self.array_format = array_format + self.nested_format = nested_format + + def parse(self, query: str) -> Mapping[str, object]: + # Note: custom format syntax is not supported yet + return parse_qs(query) + + def stringify( + self, + params: Params, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> str: + return urlencode( + self.stringify_items( + params, + array_format=array_format, + nested_format=nested_format, + ) + ) + + def stringify_items( + self, + params: Params, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> list[tuple[str, str]]: + opts = Options( + qs=self, + array_format=array_format, + nested_format=nested_format, + ) + return flatten([self._stringify_item(key, value, opts) for key, value in params.items()]) + + def _stringify_item( + self, + key: str, + value: Data, + opts: Options, + ) -> list[tuple[str, str]]: + if isinstance(value, Mapping): + items: list[tuple[str, str]] = [] + nested_format = opts.nested_format + for subkey, subvalue in value.items(): + items.extend( + self._stringify_item( + # TODO: error if unknown format + f"{key}.{subkey}" if nested_format == "dots" else f"{key}[{subkey}]", + subvalue, + opts, + ) + ) + return items + + if isinstance(value, (list, tuple)): + array_format = opts.array_format + if array_format == "comma": + return [ + ( + key, + ",".join(self._primitive_value_to_str(item) for item in value if item is not None), + ), + ] + elif array_format == "repeat": + items = [] + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + elif array_format == "indices": + 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 + "[]" + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + else: + raise NotImplementedError( + f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}" + ) + + serialised = self._primitive_value_to_str(value) + if not serialised: + return [] + return [(key, serialised)] + + def _primitive_value_to_str(self, value: PrimitiveData) -> str: + # copied from httpx + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +_qs = Querystring() +parse = _qs.parse +stringify = _qs.stringify +stringify_items = _qs.stringify_items + + +class Options: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + qs: Querystring = _qs, + *, + array_format: ArrayFormat | NotGiven = not_given, + nested_format: NestedFormat | NotGiven = not_given, + ) -> None: + self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format + self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format diff --git a/src/courier/_resource.py b/src/courier/_resource.py new file mode 100644 index 00000000..3c81c05b --- /dev/null +++ b/src/courier/_resource.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING + +import anyio + +if TYPE_CHECKING: + from ._client import Courier, AsyncCourier + + +class SyncAPIResource: + _client: Courier + + def __init__(self, client: Courier) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + def _sleep(self, seconds: float) -> None: + time.sleep(seconds) + + +class AsyncAPIResource: + _client: AsyncCourier + + def __init__(self, client: AsyncCourier) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + async def _sleep(self, seconds: float) -> None: + await anyio.sleep(seconds) diff --git a/src/courier/_response.py b/src/courier/_response.py new file mode 100644 index 00000000..f92a6b7a --- /dev/null +++ b/src/courier/_response.py @@ -0,0 +1,833 @@ +from __future__ import annotations + +import os +import inspect +import logging +import datetime +import functools +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Union, + Generic, + TypeVar, + Callable, + Iterator, + AsyncIterator, + cast, + overload, +) +from typing_extensions import Awaitable, ParamSpec, override, get_origin + +import anyio +import httpx +import pydantic + +from ._types import NoneType +from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base +from ._models import BaseModel, is_basemodel +from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER +from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type +from ._exceptions import CourierError, APIResponseValidationError + +if TYPE_CHECKING: + from ._models import FinalRequestOptions + from ._base_client import BaseClient + + +P = ParamSpec("P") +R = TypeVar("R") +_T = TypeVar("_T") +_APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]") +_AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]") + +log: logging.Logger = logging.getLogger(__name__) + + +class BaseAPIResponse(Generic[R]): + _cast_to: type[R] + _client: BaseClient[Any, Any] + _parsed_by_type: dict[type[Any], Any] + _is_sse_stream: bool + _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None + _options: FinalRequestOptions + + http_response: httpx.Response + + retries_taken: int + """The number of retries made. If no retries happened this will be `0`""" + + def __init__( + self, + *, + raw: httpx.Response, + cast_to: type[R], + client: BaseClient[Any, Any], + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + options: FinalRequestOptions, + retries_taken: int = 0, + ) -> None: + self._cast_to = cast_to + self._client = client + self._parsed_by_type = {} + self._is_sse_stream = stream + self._stream_cls = stream_cls + self._options = options + self.http_response = raw + self.retries_taken = retries_taken + + @property + def headers(self) -> httpx.Headers: + return self.http_response.headers + + @property + def http_request(self) -> httpx.Request: + """Returns the httpx Request instance associated with the current response.""" + return self.http_response.request + + @property + def status_code(self) -> int: + return self.http_response.status_code + + @property + def url(self) -> httpx.URL: + """Returns the URL for which the request was made.""" + return self.http_response.url + + @property + def method(self) -> str: + return self.http_request.method + + @property + def http_version(self) -> str: + return self.http_response.http_version + + @property + def elapsed(self) -> datetime.timedelta: + """The time taken for the complete request/response cycle to complete.""" + return self.http_response.elapsed + + @property + def is_closed(self) -> bool: + """Whether or not the response body has been closed. + + If this is False then there is response data that has not been read yet. + You must either fully consume the response body or call `.close()` + before discarding the response to prevent resource leaks. + """ + return self.http_response.is_closed + + @override + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>" + ) + + def _parse(self, *, to: type[_T] | None = None) -> R | _T: + cast_to = to if to is not None else self._cast_to + + # unwrap `TypeAlias('Name', T)` -> `T` + if is_type_alias_type(cast_to): + cast_to = cast_to.__value__ # type: ignore[unreachable] + + # unwrap `Annotated[T, ...]` -> `T` + if cast_to and is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) + + origin = get_origin(cast_to) or cast_to + + if self._is_sse_stream: + if to: + if not is_stream_class_type(to): + raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") + + return cast( + _T, + to( + cast_to=extract_stream_chunk_type( + to, + failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", + ), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if self._stream_cls: + return cast( + R, + self._stream_cls( + cast_to=extract_stream_chunk_type(self._stream_cls), + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) + if stream_cls is None: + raise MissingStreamClassError() + + return cast( + R, + stream_cls( + cast_to=cast_to, + response=self.http_response, + client=cast(Any, self._client), + options=self._options, + ), + ) + + if cast_to is NoneType: + return cast(R, None) + + response = self.http_response + if cast_to == str: + return cast(R, response.text) + + if cast_to == bytes: + return cast(R, response.content) + + if cast_to == int: + return cast(R, int(response.text)) + + if cast_to == float: + return cast(R, float(response.text)) + + if cast_to == bool: + return cast(R, response.text.lower() == "true") + + if origin == APIResponse: + raise RuntimeError("Unexpected state - cast_to is `APIResponse`") + + if inspect.isclass(origin) and issubclass(origin, httpx.Response): + # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response + # and pass that class to our request functions. We cannot change the variance to be either + # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct + # the response class ourselves but that is something that should be supported directly in httpx + # as it would be easy to incorrectly construct the Response object due to the multitude of arguments. + if cast_to != httpx.Response: + raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") + return cast(R, response) + + if ( + inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) + and not issubclass(origin, BaseModel) + and issubclass(origin, pydantic.BaseModel) + ): + raise TypeError("Pydantic models must subclass our base model type, e.g. `from courier import BaseModel`") + + if ( + cast_to is not object + and not origin is list + and not origin is dict + and not origin is Union + and not issubclass(origin, BaseModel) + ): + raise RuntimeError( + f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}." + ) + + # split is required to handle cases where additional information is included + # in the response, e.g. application/json; charset=utf-8 + content_type, *_ = response.headers.get("content-type", "*").split(";") + if not content_type.endswith("json"): + if is_basemodel(cast_to): + try: + data = response.json() + except Exception as exc: + log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) + else: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + if self._client._strict_response_validation: + raise APIResponseValidationError( + response=response, + message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", + body=response.text, + ) + + # If the API responds with content that isn't JSON then we just return + # the (decoded) text without performing any parsing so that you can still + # handle the response however you need to. + return response.text # type: ignore + + data = response.json() + + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + +class APIResponse(BaseAPIResponse[R]): + @overload + def parse(self, *, to: type[_T]) -> _T: ... + + @overload + def parse(self) -> R: ... + + def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from courier import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `int` + - `float` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + if not self._is_sse_stream: + self.read() + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed_by_type[cache_key] = parsed + return parsed + + def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return self.http_response.read() + except httpx.StreamConsumed as exc: + # The default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message. + raise StreamAlreadyConsumed() from exc + + def text(self) -> str: + """Read and decode the response content into a string.""" + self.read() + return self.http_response.text + + def json(self) -> object: + """Read and decode the JSON response content.""" + self.read() + return self.http_response.json() + + def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.http_response.close() + + def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + for chunk in self.http_response.iter_bytes(chunk_size): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + for chunk in self.http_response.iter_text(chunk_size): + yield chunk + + def iter_lines(self) -> Iterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + for chunk in self.http_response.iter_lines(): + yield chunk + + +class AsyncAPIResponse(BaseAPIResponse[R]): + @overload + async def parse(self, *, to: type[_T]) -> _T: ... + + @overload + async def parse(self) -> R: ... + + async def parse(self, *, to: type[_T] | None = None) -> R | _T: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from courier import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `httpx.Response` + """ + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] + + if not self._is_sse_stream: + await self.read() + + parsed = self._parse(to=to) + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed_by_type[cache_key] = parsed + return parsed + + async def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return await self.http_response.aread() + except httpx.StreamConsumed as exc: + # the default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message + raise StreamAlreadyConsumed() from exc + + async def text(self) -> str: + """Read and decode the response content into a string.""" + await self.read() + return self.http_response.text + + async def json(self) -> object: + """Read and decode the JSON response content.""" + await self.read() + return self.http_response.json() + + async def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.http_response.aclose() + + async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + async for chunk in self.http_response.aiter_bytes(chunk_size): + yield chunk + + async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + async for chunk in self.http_response.aiter_text(chunk_size): + yield chunk + + async def iter_lines(self) -> AsyncIterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + async for chunk in self.http_response.aiter_lines(): + yield chunk + + +class BinaryAPIResponse(APIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(): + f.write(data) + + +class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + async def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(): + await f.write(data) + + +class StreamedBinaryAPIResponse(APIResponse[bytes]): + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(chunk_size): + f.write(data) + + +class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]): + async def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(chunk_size): + await f.write(data) + + +class MissingStreamClassError(TypeError): + def __init__(self) -> None: + super().__init__( + "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `courier._streaming` for reference", + ) + + +class StreamAlreadyConsumed(CourierError): + """ + Attempted to read or stream content, but the content has already + been streamed. + + This can happen if you use a method like `.iter_lines()` and then attempt + to read th entire response body afterwards, e.g. + + ```py + response = await client.post(...) + async for line in response.iter_lines(): + ... # do something with `line` + + content = await response.read() + # ^ error + ``` + + If you want this behaviour you'll need to either manually accumulate the response + content or call `await response.read()` before iterating over the stream. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. " + "This could be due to attempting to stream the response " + "content more than once." + "\n\n" + "You can fix this by manually accumulating the response content while streaming " + "or by calling `.read()` before starting to stream." + ) + super().__init__(message) + + +class ResponseContextManager(Generic[_APIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, request_func: Callable[[], _APIResponseT]) -> None: + self._request_func = request_func + self.__response: _APIResponseT | None = None + + def __enter__(self) -> _APIResponseT: + self.__response = self._request_func() + return self.__response + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + self.__response.close() + + +class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None: + self._api_request = api_request + self.__response: _AsyncAPIResponseT | None = None + + async def __aenter__(self) -> _AsyncAPIResponseT: + self.__response = await self._api_request + return self.__response + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + await self.__response.close() + + +def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request)) + + return wrapped + + +def async_to_streamed_response_wrapper( + func: Callable[P, Awaitable[R]], +) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request)) + + return wrapped + + +def to_custom_streamed_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, ResponseContextManager[_APIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request)) + + return wrapped + + +def async_to_custom_streamed_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request)) + + return wrapped + + +def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + + kwargs["extra_headers"] = extra_headers + + return cast(APIResponse[R], func(*args, **kwargs)) + + return wrapped + + +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]: + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + + kwargs["extra_headers"] = extra_headers + + return cast(AsyncAPIResponse[R], await func(*args, **kwargs)) + + return wrapped + + +def to_custom_raw_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, _APIResponseT]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(_APIResponseT, func(*args, **kwargs)) + + return wrapped + + +def async_to_custom_raw_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, Awaitable[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs)) + + return wrapped + + +def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type: + """Given a type like `APIResponse[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(APIResponse[bytes]): + ... + + extract_response_type(MyResponse) -> bytes + ``` + """ + return extract_type_var_from_base( + typ, + generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)), + index=0, + ) diff --git a/src/courier/_streaming.py b/src/courier/_streaming.py new file mode 100644 index 00000000..b6bde76a --- /dev/null +++ b/src/courier/_streaming.py @@ -0,0 +1,338 @@ +# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py +from __future__ import annotations + +import json +import inspect +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast +from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable + +import httpx + +from ._utils import extract_type_var_from_base + +if TYPE_CHECKING: + from ._client import Courier, AsyncCourier + from ._models import FinalRequestOptions + + +_T = TypeVar("_T") + + +class Stream(Generic[_T]): + """Provides the core interface to iterate over a synchronous stream response.""" + + response: httpx.Response + _options: Optional[FinalRequestOptions] = None + _decoder: SSEBytesDecoder + + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: Courier, + options: Optional[FinalRequestOptions] = None, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._options = options + self._decoder = client._make_sse_decoder() + self._iterator = self.__stream__() + + def __next__(self) -> _T: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[_T]: + for item in self._iterator: + yield item + + def _iter_events(self) -> Iterator[ServerSentEvent]: + yield from self._decoder.iter_bytes(self.response.iter_bytes()) + + def __stream__(self) -> Iterator[_T]: + cast_to = cast(Any, self._cast_to) + response = self.response + process_data = self._client._process_response_data + iterator = self._iter_events() + + try: + for sse in iterator: + yield process_data(data=sse.json(), cast_to=cast_to, response=response) + finally: + # Ensure the response is closed even if the consumer doesn't read all data + response.close() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.response.close() + + +class AsyncStream(Generic[_T]): + """Provides the core interface to iterate over an asynchronous stream response.""" + + response: httpx.Response + _options: Optional[FinalRequestOptions] = None + _decoder: SSEDecoder | SSEBytesDecoder + + def __init__( + self, + *, + cast_to: type[_T], + response: httpx.Response, + client: AsyncCourier, + options: Optional[FinalRequestOptions] = None, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._options = options + self._decoder = client._make_sse_decoder() + self._iterator = self.__stream__() + + async def __anext__(self) -> _T: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[_T]: + async for item in self._iterator: + yield item + + async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: + async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()): + yield sse + + async def __stream__(self) -> AsyncIterator[_T]: + cast_to = cast(Any, self._cast_to) + response = self.response + process_data = self._client._process_response_data + iterator = self._iter_events() + + try: + async for sse in iterator: + yield process_data(data=sse.json(), cast_to=cast_to, response=response) + finally: + # Ensure the response is closed even if the consumer doesn't read all data + await response.aclose() + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.response.aclose() + + +class ServerSentEvent: + def __init__( + self, + *, + event: str | None = None, + data: str | None = None, + id: str | None = None, + retry: int | None = None, + ) -> None: + if data is None: + data = "" + + self._id = id + self._data = data + self._event = event or None + self._retry = retry + + @property + def event(self) -> str | None: + return self._event + + @property + def id(self) -> str | None: + return self._id + + @property + def retry(self) -> int | None: + return self._retry + + @property + def data(self) -> str: + return self._data + + def json(self) -> Any: + return json.loads(self.data) + + @override + def __repr__(self) -> str: + return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})" + + +class SSEDecoder: + _data: list[str] + _event: str | None + _retry: int | None + _last_event_id: str | None + + def __init__(self) -> None: + self._event = None + self._data = [] + self._last_event_id = None + self._retry = None + + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + for chunk in self._iter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + async for chunk in self._aiter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + async for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + def decode(self, line: str) -> ServerSentEvent | None: + # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 + + if not line: + if not self._event and not self._data and not self._last_event_id and self._retry is None: + return None + + sse = ServerSentEvent( + event=self._event, + data="\n".join(self._data), + id=self._last_event_id, + retry=self._retry, + ) + + # NOTE: as per the SSE spec, do not reset last_event_id. + self._event = None + self._data = [] + self._retry = None + + return sse + + if line.startswith(":"): + return None + + fieldname, _, value = line.partition(":") + + if value.startswith(" "): + value = value[1:] + + if fieldname == "event": + self._event = value + elif fieldname == "data": + self._data.append(value) + elif fieldname == "id": + if "\0" in value: + pass + else: + self._last_event_id = value + elif fieldname == "retry": + try: + self._retry = int(value) + except (TypeError, ValueError): + pass + else: + pass # Field is ignored. + + return None + + +@runtime_checkable +class SSEBytesDecoder(Protocol): + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + +def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]: + """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`""" + origin = get_origin(typ) or typ + return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream)) + + +def extract_stream_chunk_type( + stream_cls: type, + *, + failure_message: str | None = None, +) -> type: + """Given a type like `Stream[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyStream(Stream[bytes]): + ... + + extract_stream_chunk_type(MyStream) -> bytes + ``` + """ + from ._base_client import Stream, AsyncStream + + return extract_type_var_from_base( + stream_cls, + index=0, + generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), + failure_message=failure_message, + ) diff --git a/src/courier/_types.py b/src/courier/_types.py new file mode 100644 index 00000000..512a4f11 --- /dev/null +++ b/src/courier/_types.py @@ -0,0 +1,273 @@ +from __future__ import annotations + +from os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + Dict, + List, + Type, + Tuple, + Union, + Mapping, + TypeVar, + Callable, + Iterable, + Iterator, + Optional, + Sequence, + AsyncIterable, +) +from typing_extensions import ( + Set, + Literal, + Protocol, + TypeAlias, + TypedDict, + SupportsIndex, + overload, + override, + runtime_checkable, +) + +import httpx +import pydantic +from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport + +if TYPE_CHECKING: + from ._models import BaseModel + from ._response import APIResponse, AsyncAPIResponse + +Transport = BaseTransport +AsyncTransport = AsyncBaseTransport +Query = Mapping[str, object] +Body = object +AnyMapping = Mapping[str, object] +ModelT = TypeVar("ModelT", bound=pydantic.BaseModel) +_T = TypeVar("_T") + +ArrayFormat = Literal["comma", "repeat", "indices", "brackets"] +NestedFormat = Literal["dots", "brackets"] + + +# Approximates httpx internal ProxiesTypes and RequestFiles types +# while adding support for `PathLike` instances +ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]] +ProxiesTypes = Union[str, Proxy, ProxiesDict] +if TYPE_CHECKING: + Base64FileInput = Union[IO[bytes], PathLike[str]] + FileContent = Union[IO[bytes], bytes, PathLike[str]] +else: + Base64FileInput = Union[IO[bytes], PathLike] + FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8. + + +# Used for sending raw binary data / streaming data in request bodies +# e.g. for file uploads without multipart encoding +BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]] +AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]] + +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +# duplicate of the above but without our custom file support +HttpxFileContent = Union[IO[bytes], bytes] +HttpxFileTypes = Union[ + # file (or bytes) + HttpxFileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], HttpxFileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], HttpxFileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]], +] +HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]] + +# Workaround to support (cast_to: Type[ResponseT]) -> ResponseT +# where ResponseT includes `None`. In order to support directly +# passing `None`, overloads would have to be defined for every +# method that uses `ResponseT` which would lead to an unacceptable +# amount of code duplication and make it unreadable. See _base_client.py +# for example usage. +# +# This unfortunately means that you will either have +# to import this type and pass it explicitly: +# +# from courier import NoneType +# client.get('/foo', cast_to=NoneType) +# +# or build it yourself: +# +# client.get('/foo', cast_to=type(None)) +if TYPE_CHECKING: + NoneType: Type[None] +else: + NoneType = type(None) + + +class RequestOptions(TypedDict, total=False): + headers: Headers + max_retries: int + timeout: float | Timeout | None + params: Query + extra_json: AnyMapping + idempotency_key: str + follow_redirects: bool + + +# Sentinel class used until PEP 0661 is accepted +class NotGiven: + """ + For parameters with a meaningful None value, we need to distinguish between + the user explicitly passing None, and the user not passing the parameter at + all. + + User code shouldn't need to use not_given directly. + + For example: + + ```py + def create(timeout: Timeout | None | NotGiven = not_given): ... + + + create(timeout=1) # 1s timeout + create(timeout=None) # No timeout + create() # Default timeout behavior + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + @override + def __repr__(self) -> str: + return "NOT_GIVEN" + + +not_given = NotGiven() +# for backwards compatibility: +NOT_GIVEN = NotGiven() + + +class Omit: + """ + To explicitly omit something from being sent in a request, use `omit`. + + ```py + # as the default `Content-Type` header is `application/json` that will be sent + client.post("/upload/files", files={"file": b"my raw file content"}) + + # you can't explicitly override the header as it has to be dynamically generated + # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983' + client.post(..., headers={"Content-Type": "multipart/form-data"}) + + # instead you can remove the default `application/json` header by passing omit + client.post(..., headers={"Content-Type": omit}) + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + +omit = Omit() + + +@runtime_checkable +class ModelBuilderProtocol(Protocol): + @classmethod + def build( + cls: type[_T], + *, + response: Response, + data: object, + ) -> _T: ... + + +Headers = Mapping[str, Union[str, Omit]] + + +class HeadersLikeProtocol(Protocol): + def get(self, __key: str) -> str | None: ... + + +HeadersLike = Union[Headers, HeadersLikeProtocol] + +ResponseT = TypeVar( + "ResponseT", + bound=Union[ + object, + str, + None, + "BaseModel", + List[Any], + Dict[str, Any], + Response, + ModelBuilderProtocol, + "APIResponse[Any]", + "AsyncAPIResponse[Any]", + ], +) + +StrBytesIntFloat = Union[str, bytes, int, float] + +# Note: copied from Pydantic +# https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79 +IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]] + +PostParser = Callable[[Any], Any] + + +@runtime_checkable +class InheritsGeneric(Protocol): + """Represents a type that has inherited from `Generic` + + The `__orig_bases__` property can be used to determine the resolved + type variable for a given base class. + """ + + __orig_bases__: tuple[_GenericAlias] + + +class _GenericAlias(Protocol): + __origin__: type[object] + + +class HttpxSendArgs(TypedDict, total=False): + auth: httpx.Auth + follow_redirects: bool + + +_T_co = TypeVar("_T_co", covariant=True) + + +if TYPE_CHECKING: + # This works because str.__contains__ does not accept object (either in typeshed or at runtime) + # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285 + # + # Note: index() and count() methods are intentionally omitted to allow pyright to properly + # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr. + class SequenceNotStr(Protocol[_T_co]): + @overload + def __getitem__(self, index: SupportsIndex, /) -> _T_co: ... + @overload + def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ... + def __contains__(self, value: object, /) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... +else: + # just point this to a normal `Sequence` at runtime to avoid having to special case + # deserializing our custom sequence type + SequenceNotStr = Sequence diff --git a/src/courier/_utils/__init__.py b/src/courier/_utils/__init__.py new file mode 100644 index 00000000..1c090e51 --- /dev/null +++ b/src/courier/_utils/__init__.py @@ -0,0 +1,64 @@ +from ._path import path_template as path_template +from ._sync import asyncify as asyncify +from ._proxy import LazyProxy as LazyProxy +from ._utils import ( + flatten as flatten, + is_dict as is_dict, + is_list as is_list, + is_given as is_given, + is_tuple as is_tuple, + json_safe as json_safe, + lru_cache as lru_cache, + is_mapping as is_mapping, + is_tuple_t as is_tuple_t, + is_iterable as is_iterable, + is_sequence as is_sequence, + coerce_float as coerce_float, + is_mapping_t as is_mapping_t, + removeprefix as removeprefix, + removesuffix as removesuffix, + extract_files as extract_files, + is_sequence_t as is_sequence_t, + required_args as required_args, + coerce_boolean as coerce_boolean, + coerce_integer as coerce_integer, + file_from_path as file_from_path, + strip_not_given as strip_not_given, + get_async_library as get_async_library, + maybe_coerce_float as maybe_coerce_float, + get_required_header as get_required_header, + maybe_coerce_boolean as maybe_coerce_boolean, + maybe_coerce_integer as maybe_coerce_integer, +) +from ._compat import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, +) +from ._typing import ( + is_list_type as is_list_type, + is_union_type as is_union_type, + extract_type_arg as extract_type_arg, + is_iterable_type as is_iterable_type, + is_required_type as is_required_type, + is_sequence_type as is_sequence_type, + is_annotated_type as is_annotated_type, + is_type_alias_type as is_type_alias_type, + strip_annotated_type as strip_annotated_type, + extract_type_var_from_base as extract_type_var_from_base, +) +from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator +from ._transform import ( + PropertyInfo as PropertyInfo, + transform as transform, + async_transform as async_transform, + maybe_transform as maybe_transform, + async_maybe_transform as async_maybe_transform, +) +from ._reflection import ( + function_has_argument as function_has_argument, + assert_signatures_in_sync as assert_signatures_in_sync, +) +from ._datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime diff --git a/src/courier/_utils/_compat.py b/src/courier/_utils/_compat.py new file mode 100644 index 00000000..2c70b299 --- /dev/null +++ b/src/courier/_utils/_compat.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import sys +import typing_extensions +from typing import Any, Type, Union, Literal, Optional +from datetime import date, datetime +from typing_extensions import get_args as _get_args, get_origin as _get_origin + +from .._types import StrBytesIntFloat +from ._datetime_parse import parse_date as _parse_date, parse_datetime as _parse_datetime + +_LITERAL_TYPES = {Literal, typing_extensions.Literal} + + +def get_args(tp: type[Any]) -> tuple[Any, ...]: + return _get_args(tp) + + +def get_origin(tp: type[Any]) -> type[Any] | None: + return _get_origin(tp) + + +def is_union(tp: Optional[Type[Any]]) -> bool: + if sys.version_info < (3, 10): + return tp is Union # type: ignore[comparison-overlap] + else: + import types + + return tp is Union or tp is types.UnionType # type: ignore[comparison-overlap] + + +def is_typeddict(tp: Type[Any]) -> bool: + return typing_extensions.is_typeddict(tp) + + +def is_literal_type(tp: Type[Any]) -> bool: + return get_origin(tp) in _LITERAL_TYPES + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + return _parse_date(value) + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + return _parse_datetime(value) diff --git a/src/courier/_utils/_datetime_parse.py b/src/courier/_utils/_datetime_parse.py new file mode 100644 index 00000000..7cb9d9e6 --- /dev/null +++ b/src/courier/_utils/_datetime_parse.py @@ -0,0 +1,136 @@ +""" +This file contains code from https://github.com/pydantic/pydantic/blob/main/pydantic/v1/datetime_parse.py +without the Pydantic v1 specific errors. +""" + +from __future__ import annotations + +import re +from typing import Dict, Union, Optional +from datetime import date, datetime, timezone, timedelta + +from .._types import StrBytesIntFloat + +date_expr = r"(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})" +time_expr = ( + r"(?P\d{1,2}):(?P\d{1,2})" + r"(?::(?P\d{1,2})(?:\.(?P\d{1,6})\d{0,6})?)?" + r"(?PZ|[+-]\d{2}(?::?\d{2})?)?$" +) + +date_re = re.compile(f"{date_expr}$") +datetime_re = re.compile(f"{date_expr}[T ]{time_expr}") + + +EPOCH = datetime(1970, 1, 1) +# if greater than this, the number is in ms, if less than or equal it's in seconds +# (in seconds this is 11th October 2603, in ms it's 20th August 1970) +MS_WATERSHED = int(2e10) +# slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 +MAX_NUMBER = int(3e20) + + +def _get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]: + if isinstance(value, (int, float)): + return value + try: + return float(value) + except ValueError: + return None + except TypeError: + raise TypeError(f"invalid type; expected {native_expected_type}, string, bytes, int or float") from None + + +def _from_unix_seconds(seconds: Union[int, float]) -> datetime: + if seconds > MAX_NUMBER: + return datetime.max + elif seconds < -MAX_NUMBER: + return datetime.min + + while abs(seconds) > MS_WATERSHED: + seconds /= 1000 + dt = EPOCH + timedelta(seconds=seconds) + return dt.replace(tzinfo=timezone.utc) + + +def _parse_timezone(value: Optional[str]) -> Union[None, int, timezone]: + if value == "Z": + return timezone.utc + elif value is not None: + offset_mins = int(value[-2:]) if len(value) > 3 else 0 + offset = 60 * int(value[1:3]) + offset_mins + if value[0] == "-": + offset = -offset + return timezone(timedelta(minutes=offset)) + else: + return None + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + """ + Parse a datetime/int/float/string and return a datetime.datetime. + + This function supports time zone offsets. When the input contains one, + the output uses a timezone with a fixed offset from UTC. + + Raise ValueError if the input is well formatted but not a valid datetime. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, datetime): + return value + + number = _get_numeric(value, "datetime") + if number is not None: + return _from_unix_seconds(number) + + if isinstance(value, bytes): + value = value.decode() + + assert not isinstance(value, (float, int)) + + match = datetime_re.match(value) + if match is None: + raise ValueError("invalid datetime format") + + kw = match.groupdict() + if kw["microsecond"]: + kw["microsecond"] = kw["microsecond"].ljust(6, "0") + + tzinfo = _parse_timezone(kw.pop("tzinfo")) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + kw_["tzinfo"] = tzinfo + + return datetime(**kw_) # type: ignore + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + """ + Parse a date/int/float/string and return a datetime.date. + + Raise ValueError if the input is well formatted but not a valid date. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, date): + if isinstance(value, datetime): + return value.date() + else: + return value + + number = _get_numeric(value, "date") + if number is not None: + return _from_unix_seconds(number).date() + + if isinstance(value, bytes): + value = value.decode() + + assert not isinstance(value, (float, int)) + match = date_re.match(value) + if match is None: + raise ValueError("invalid date format") + + kw = {k: int(v) for k, v in match.groupdict().items()} + + try: + return date(**kw) + except ValueError: + raise ValueError("invalid date format") from None diff --git a/src/courier/_utils/_json.py b/src/courier/_utils/_json.py new file mode 100644 index 00000000..60584214 --- /dev/null +++ b/src/courier/_utils/_json.py @@ -0,0 +1,35 @@ +import json +from typing import Any +from datetime import datetime +from typing_extensions import override + +import pydantic + +from .._compat import model_dump + + +def openapi_dumps(obj: Any) -> bytes: + """ + Serialize an object to UTF-8 encoded JSON bytes. + + Extends the standard json.dumps with support for additional types + commonly used in the SDK, such as `datetime`, `pydantic.BaseModel`, etc. + """ + return json.dumps( + obj, + cls=_CustomEncoder, + # Uses the same defaults as httpx's JSON serialization + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False, + ).encode() + + +class _CustomEncoder(json.JSONEncoder): + @override + def default(self, o: Any) -> Any: + if isinstance(o, datetime): + return o.isoformat() + if isinstance(o, pydantic.BaseModel): + return model_dump(o, exclude_unset=True, mode="json", by_alias=True) + return super().default(o) diff --git a/src/courier/_utils/_logs.py b/src/courier/_utils/_logs.py new file mode 100644 index 00000000..1676fea3 --- /dev/null +++ b/src/courier/_utils/_logs.py @@ -0,0 +1,25 @@ +import os +import logging + +logger: logging.Logger = logging.getLogger("courier") +httpx_logger: logging.Logger = logging.getLogger("httpx") + + +def _basic_config() -> None: + # e.g. [2023-10-05 14:12:26 - courier._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK" + logging.basicConfig( + format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + +def setup_logging() -> None: + env = os.environ.get("COURIER_LOG") + if env == "debug": + _basic_config() + logger.setLevel(logging.DEBUG) + httpx_logger.setLevel(logging.DEBUG) + elif env == "info": + _basic_config() + logger.setLevel(logging.INFO) + httpx_logger.setLevel(logging.INFO) diff --git a/src/courier/_utils/_path.py b/src/courier/_utils/_path.py new file mode 100644 index 00000000..4d6e1e4c --- /dev/null +++ b/src/courier/_utils/_path.py @@ -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 + + 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 diff --git a/src/courier/_utils/_proxy.py b/src/courier/_utils/_proxy.py new file mode 100644 index 00000000..0f239a33 --- /dev/null +++ b/src/courier/_utils/_proxy.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Generic, TypeVar, Iterable, cast +from typing_extensions import override + +T = TypeVar("T") + + +class LazyProxy(Generic[T], ABC): + """Implements data methods to pretend that an instance is another instance. + + This includes forwarding attribute access and other methods. + """ + + # Note: we have to special case proxies that themselves return proxies + # to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz` + + def __getattr__(self, attr: str) -> object: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied # pyright: ignore + return getattr(proxied, attr) + + @override + def __repr__(self) -> str: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied.__class__.__name__ + return repr(self.__get_proxied__()) + + @override + def __str__(self) -> str: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied.__class__.__name__ + return str(proxied) + + @override + def __dir__(self) -> Iterable[str]: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return [] + return proxied.__dir__() + + @property # type: ignore + @override + def __class__(self) -> type: # pyright: ignore + try: + proxied = self.__get_proxied__() + except Exception: + return type(self) + if issubclass(type(proxied), LazyProxy): + return type(proxied) + return proxied.__class__ + + def __get_proxied__(self) -> T: + return self.__load__() + + def __as_proxied__(self) -> T: + """Helper method that returns the current proxy, typed as the loaded object""" + return cast(T, self) + + @abstractmethod + def __load__(self) -> T: ... diff --git a/src/courier/_utils/_reflection.py b/src/courier/_utils/_reflection.py new file mode 100644 index 00000000..89aa712a --- /dev/null +++ b/src/courier/_utils/_reflection.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import inspect +from typing import Any, Callable + + +def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool: + """Returns whether or not the given function has a specific parameter""" + sig = inspect.signature(func) + return arg_name in sig.parameters + + +def assert_signatures_in_sync( + source_func: Callable[..., Any], + check_func: Callable[..., Any], + *, + exclude_params: set[str] = set(), +) -> None: + """Ensure that the signature of the second function matches the first.""" + + check_sig = inspect.signature(check_func) + source_sig = inspect.signature(source_func) + + errors: list[str] = [] + + for name, source_param in source_sig.parameters.items(): + if name in exclude_params: + continue + + custom_param = check_sig.parameters.get(name) + if not custom_param: + errors.append(f"the `{name}` param is missing") + continue + + if custom_param.annotation != source_param.annotation: + errors.append( + f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}" + ) + continue + + if errors: + raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors)) diff --git a/src/courier/_utils/_resources_proxy.py b/src/courier/_utils/_resources_proxy.py new file mode 100644 index 00000000..ebf9f5fe --- /dev/null +++ b/src/courier/_utils/_resources_proxy.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import Any +from typing_extensions import override + +from ._proxy import LazyProxy + + +class ResourcesProxy(LazyProxy[Any]): + """A proxy for the `courier.resources` module. + + This is used so that we can lazily import `courier.resources` only when + needed *and* so that users can just import `courier` and reference `courier.resources` + """ + + @override + def __load__(self) -> Any: + import importlib + + mod = importlib.import_module("courier.resources") + return mod + + +resources = ResourcesProxy().__as_proxied__() diff --git a/src/courier/_utils/_streams.py b/src/courier/_utils/_streams.py new file mode 100644 index 00000000..f4a0208f --- /dev/null +++ b/src/courier/_utils/_streams.py @@ -0,0 +1,12 @@ +from typing import Any +from typing_extensions import Iterator, AsyncIterator + + +def consume_sync_iterator(iterator: Iterator[Any]) -> None: + for _ in iterator: + ... + + +async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None: + async for _ in iterator: + ... diff --git a/src/courier/_utils/_sync.py b/src/courier/_utils/_sync.py new file mode 100644 index 00000000..f6027c18 --- /dev/null +++ b/src/courier/_utils/_sync.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import asyncio +import functools +from typing import TypeVar, Callable, Awaitable +from typing_extensions import ParamSpec + +import anyio +import sniffio +import anyio.to_thread + +T_Retval = TypeVar("T_Retval") +T_ParamSpec = ParamSpec("T_ParamSpec") + + +async def to_thread( + func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs +) -> T_Retval: + if sniffio.current_async_library() == "asyncio": + return await asyncio.to_thread(func, *args, **kwargs) + + return await anyio.to_thread.run_sync( + functools.partial(func, *args, **kwargs), + ) + + +# inspired by `asyncer`, https://github.com/tiangolo/asyncer +def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: + """ + Take a blocking function and create an async one that receives the same + positional and keyword arguments. + + Usage: + + ```python + def blocking_func(arg1, arg2, kwarg1=None): + # blocking code + return result + + + result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1) + ``` + + ## Arguments + + `function`: a blocking regular callable (e.g. a function) + + ## Return + + An async function that takes the same positional and keyword arguments as the + original one, that when called runs the same original function in a thread worker + and returns the result. + """ + + async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: + return await to_thread(function, *args, **kwargs) + + return wrapper diff --git a/src/courier/_utils/_transform.py b/src/courier/_utils/_transform.py new file mode 100644 index 00000000..52075492 --- /dev/null +++ b/src/courier/_utils/_transform.py @@ -0,0 +1,457 @@ +from __future__ import annotations + +import io +import base64 +import pathlib +from typing import Any, Mapping, TypeVar, cast +from datetime import date, datetime +from typing_extensions import Literal, get_args, override, get_type_hints as _get_type_hints + +import anyio +import pydantic + +from ._utils import ( + is_list, + is_given, + lru_cache, + is_mapping, + is_iterable, + is_sequence, +) +from .._files import is_base64_file_input +from ._compat import get_origin, is_typeddict +from ._typing import ( + is_list_type, + is_union_type, + extract_type_arg, + is_iterable_type, + is_required_type, + is_sequence_type, + is_annotated_type, + strip_annotated_type, +) + +_T = TypeVar("_T") + + +# TODO: support for drilling globals() and locals() +# TODO: ensure works correctly with forward references in all cases + + +PropertyFormat = Literal["iso8601", "base64", "custom"] + + +class PropertyInfo: + """Metadata class to be used in Annotated types to provide information about a given type. + + For example: + + class MyParams(TypedDict): + account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')] + + This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API. + """ + + alias: str | None + format: PropertyFormat | None + format_template: str | None + discriminator: str | None + + def __init__( + self, + *, + alias: str | None = None, + format: PropertyFormat | None = None, + format_template: str | None = None, + discriminator: str | None = None, + ) -> None: + self.alias = alias + self.format = format + self.format_template = format_template + self.discriminator = discriminator + + @override + def __repr__(self) -> str: + return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')" + + +def maybe_transform( + data: object, + expected_type: object, +) -> Any | None: + """Wrapper over `transform()` that allows `None` to be passed. + + See `transform()` for more details. + """ + if data is None: + return None + return transform(data, expected_type) + + +# Wrapper over _transform_recursive providing fake types +def transform( + data: _T, + expected_type: object, +) -> _T: + """Transform dictionaries based off of type information from the given type, for example: + + ```py + class Params(TypedDict, total=False): + card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]] + + + transformed = transform({"card_id": ""}, Params) + # {'cardID': ''} + ``` + + Any keys / data that does not have type information given will be included as is. + + It should be noted that the transformations that this function does are not represented in the type system. + """ + transformed = _transform_recursive(data, annotation=cast(type, expected_type)) + return cast(_T, transformed) + + +@lru_cache(maxsize=8096) +def _get_annotated_type(type_: type) -> type | None: + """If the given type is an `Annotated` type then it is returned, if not `None` is returned. + + This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]` + """ + if is_required_type(type_): + # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]` + type_ = get_args(type_)[0] + + if is_annotated_type(type_): + return type_ + + return None + + +def _maybe_transform_key(key: str, type_: type) -> str: + """Transform the given `data` based on the annotations provided in `type_`. + + Note: this function only looks at `Annotated` types that contain `PropertyInfo` metadata. + """ + annotated_type = _get_annotated_type(type_) + if annotated_type is None: + # no `Annotated` definition for this type, no transformation needed + return key + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.alias is not None: + return annotation.alias + + return key + + +def _no_transform_needed(annotation: type) -> bool: + return annotation == float or annotation == int + + +def _transform_recursive( + data: object, + *, + annotation: type, + inner_type: type | None = None, +) -> object: + """Transform the given data against the expected type. + + Args: + annotation: The direct type annotation given to the particular piece of data. + This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc + + inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type + is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in + the list can be transformed using the metadata from the container type. + + Defaults to the same value as the `annotation` argument. + """ + from .._compat import model_dump + + if inner_type is None: + inner_type = annotation + + stripped_type = strip_annotated_type(inner_type) + origin = get_origin(stripped_type) or stripped_type + if is_typeddict(stripped_type) and is_mapping(data): + return _transform_typeddict(data, stripped_type) + + if origin == dict and is_mapping(data): + items_type = get_args(stripped_type)[1] + return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()} + + if ( + # List[T] + (is_list_type(stripped_type) and is_list(data)) + # Iterable[T] + or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + # Sequence[T] + or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str)) + ): + # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually + # intended as an iterable, so we don't transform it. + if isinstance(data, dict): + return cast(object, data) + + inner_type = extract_type_arg(stripped_type, 0) + if _no_transform_needed(inner_type): + # for some types there is no need to transform anything, so we can get a small + # perf boost from skipping that work. + # + # but we still need to convert to a list to ensure the data is json-serializable + if is_list(data): + return data + return list(data) + + return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] + + if is_union_type(stripped_type): + # For union types we run the transformation against all subtypes to ensure that everything is transformed. + # + # TODO: there may be edge cases where the same normalized field name will transform to two different names + # in different subtypes. + for subtype in get_args(stripped_type): + data = _transform_recursive(data, annotation=annotation, inner_type=subtype) + return data + + if isinstance(data, pydantic.BaseModel): + return model_dump(data, exclude_unset=True, mode="json") + + annotated_type = _get_annotated_type(annotation) + if annotated_type is None: + return data + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.format is not None: + return _format_data(data, annotation.format, annotation.format_template) + + return data + + +def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object: + if isinstance(data, (date, datetime)): + if format_ == "iso8601": + return data.isoformat() + + if format_ == "custom" and format_template is not None: + return data.strftime(format_template) + + if format_ == "base64" and is_base64_file_input(data): + binary: str | bytes | None = None + + if isinstance(data, pathlib.Path): + binary = data.read_bytes() + elif isinstance(data, io.IOBase): + binary = data.read() + + if isinstance(binary, str): # type: ignore[unreachable] + binary = binary.encode() + + if not isinstance(binary, bytes): + raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}") + + return base64.b64encode(binary).decode("ascii") + + return data + + +def _transform_typeddict( + data: Mapping[str, object], + expected_type: type, +) -> Mapping[str, object]: + result: dict[str, object] = {} + annotations = get_type_hints(expected_type, include_extras=True) + for key, value in data.items(): + if not is_given(value): + # we don't need to include omitted values here as they'll + # be stripped out before the request is sent anyway + continue + + type_ = annotations.get(key) + if type_ is None: + # we do not have a type annotation for this field, leave it as is + result[key] = value + else: + result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_) + return result + + +async def async_maybe_transform( + data: object, + expected_type: object, +) -> Any | None: + """Wrapper over `async_transform()` that allows `None` to be passed. + + See `async_transform()` for more details. + """ + if data is None: + return None + return await async_transform(data, expected_type) + + +async def async_transform( + data: _T, + expected_type: object, +) -> _T: + """Transform dictionaries based off of type information from the given type, for example: + + ```py + class Params(TypedDict, total=False): + card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]] + + + transformed = transform({"card_id": ""}, Params) + # {'cardID': ''} + ``` + + Any keys / data that does not have type information given will be included as is. + + It should be noted that the transformations that this function does are not represented in the type system. + """ + transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type)) + return cast(_T, transformed) + + +async def _async_transform_recursive( + data: object, + *, + annotation: type, + inner_type: type | None = None, +) -> object: + """Transform the given data against the expected type. + + Args: + annotation: The direct type annotation given to the particular piece of data. + This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc + + inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type + is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in + the list can be transformed using the metadata from the container type. + + Defaults to the same value as the `annotation` argument. + """ + from .._compat import model_dump + + if inner_type is None: + inner_type = annotation + + stripped_type = strip_annotated_type(inner_type) + origin = get_origin(stripped_type) or stripped_type + if is_typeddict(stripped_type) and is_mapping(data): + return await _async_transform_typeddict(data, stripped_type) + + if origin == dict and is_mapping(data): + items_type = get_args(stripped_type)[1] + return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()} + + if ( + # List[T] + (is_list_type(stripped_type) and is_list(data)) + # Iterable[T] + or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + # Sequence[T] + or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str)) + ): + # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually + # intended as an iterable, so we don't transform it. + if isinstance(data, dict): + return cast(object, data) + + inner_type = extract_type_arg(stripped_type, 0) + if _no_transform_needed(inner_type): + # for some types there is no need to transform anything, so we can get a small + # perf boost from skipping that work. + # + # but we still need to convert to a list to ensure the data is json-serializable + if is_list(data): + return data + return list(data) + + return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] + + if is_union_type(stripped_type): + # For union types we run the transformation against all subtypes to ensure that everything is transformed. + # + # TODO: there may be edge cases where the same normalized field name will transform to two different names + # in different subtypes. + for subtype in get_args(stripped_type): + data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype) + return data + + if isinstance(data, pydantic.BaseModel): + return model_dump(data, exclude_unset=True, mode="json") + + annotated_type = _get_annotated_type(annotation) + if annotated_type is None: + return data + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.format is not None: + return await _async_format_data(data, annotation.format, annotation.format_template) + + return data + + +async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object: + if isinstance(data, (date, datetime)): + if format_ == "iso8601": + return data.isoformat() + + if format_ == "custom" and format_template is not None: + return data.strftime(format_template) + + if format_ == "base64" and is_base64_file_input(data): + binary: str | bytes | None = None + + if isinstance(data, pathlib.Path): + binary = await anyio.Path(data).read_bytes() + elif isinstance(data, io.IOBase): + binary = data.read() + + if isinstance(binary, str): # type: ignore[unreachable] + binary = binary.encode() + + if not isinstance(binary, bytes): + raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}") + + return base64.b64encode(binary).decode("ascii") + + return data + + +async def _async_transform_typeddict( + data: Mapping[str, object], + expected_type: type, +) -> Mapping[str, object]: + result: dict[str, object] = {} + annotations = get_type_hints(expected_type, include_extras=True) + for key, value in data.items(): + if not is_given(value): + # we don't need to include omitted values here as they'll + # be stripped out before the request is sent anyway + continue + + type_ = annotations.get(key) + if type_ is None: + # we do not have a type annotation for this field, leave it as is + result[key] = value + else: + result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_) + return result + + +@lru_cache(maxsize=8096) +def get_type_hints( + obj: Any, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, +) -> dict[str, Any]: + return _get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras) diff --git a/src/courier/_utils/_typing.py b/src/courier/_utils/_typing.py new file mode 100644 index 00000000..193109f3 --- /dev/null +++ b/src/courier/_utils/_typing.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import sys +import typing +import typing_extensions +from typing import Any, TypeVar, Iterable, cast +from collections import abc as _c_abc +from typing_extensions import ( + TypeIs, + Required, + Annotated, + get_args, + get_origin, +) + +from ._utils import lru_cache +from .._types import InheritsGeneric +from ._compat import is_union as _is_union + + +def is_annotated_type(typ: type) -> bool: + return get_origin(typ) == Annotated + + +def is_list_type(typ: type) -> bool: + return (get_origin(typ) or typ) == list + + +def is_sequence_type(typ: type) -> bool: + origin = get_origin(typ) or typ + return origin == typing_extensions.Sequence or origin == typing.Sequence or origin == _c_abc.Sequence + + +def is_iterable_type(typ: type) -> bool: + """If the given type is `typing.Iterable[T]`""" + origin = get_origin(typ) or typ + return origin == Iterable or origin == _c_abc.Iterable + + +def is_union_type(typ: type) -> bool: + return _is_union(get_origin(typ)) + + +def is_required_type(typ: type) -> bool: + return get_origin(typ) == Required + + +def is_typevar(typ: type) -> bool: + # type ignore is required because type checkers + # think this expression will always return False + return type(typ) == TypeVar # type: ignore + + +_TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,) +if sys.version_info >= (3, 12): + _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType) + + +def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]: + """Return whether the provided argument is an instance of `TypeAliasType`. + + ```python + type Int = int + is_type_alias_type(Int) + # > True + Str = TypeAliasType("Str", str) + is_type_alias_type(Str) + # > True + ``` + """ + return isinstance(tp, _TYPE_ALIAS_TYPES) + + +# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] +@lru_cache(maxsize=8096) +def strip_annotated_type(typ: type) -> type: + if is_required_type(typ) or is_annotated_type(typ): + return strip_annotated_type(cast(type, get_args(typ)[0])) + + return typ + + +def extract_type_arg(typ: type, index: int) -> type: + args = get_args(typ) + try: + return cast(type, args[index]) + except IndexError as err: + raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err + + +def extract_type_var_from_base( + typ: type, + *, + generic_bases: tuple[type, ...], + index: int, + failure_message: str | None = None, +) -> type: + """Given a type like `Foo[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(Foo[bytes]): + ... + + extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes + ``` + + And where a generic subclass is given: + ```py + _T = TypeVar('_T') + class MyResponse(Foo[_T]): + ... + + extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes + ``` + """ + cls = cast(object, get_origin(typ) or typ) + if cls in generic_bases: # pyright: ignore[reportUnnecessaryContains] + # we're given the class directly + return extract_type_arg(typ, index) + + # if a subclass is given + # --- + # this is needed as __orig_bases__ is not present in the typeshed stubs + # because it is intended to be for internal use only, however there does + # not seem to be a way to resolve generic TypeVars for inherited subclasses + # without using it. + if isinstance(cls, InheritsGeneric): + target_base_class: Any | None = None + for base in cls.__orig_bases__: + if base.__origin__ in generic_bases: + target_base_class = base + break + + if target_base_class is None: + raise RuntimeError( + "Could not find the generic base class;\n" + "This should never happen;\n" + f"Does {cls} inherit from one of {generic_bases} ?" + ) + + extracted = extract_type_arg(target_base_class, index) + if is_typevar(extracted): + # If the extracted type argument is itself a type variable + # then that means the subclass itself is generic, so we have + # to resolve the type argument from the class itself, not + # the base class. + # + # Note: if there is more than 1 type argument, the subclass could + # change the ordering of the type arguments, this is not currently + # supported. + return extract_type_arg(typ, index) + + return extracted + + raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}") diff --git a/src/courier/_utils/_utils.py b/src/courier/_utils/_utils.py new file mode 100644 index 00000000..199cd231 --- /dev/null +++ b/src/courier/_utils/_utils.py @@ -0,0 +1,433 @@ +from __future__ import annotations + +import os +import re +import inspect +import functools +from typing import ( + Any, + Tuple, + Mapping, + TypeVar, + Callable, + Iterable, + Sequence, + cast, + overload, +) +from pathlib import Path +from datetime import date, datetime +from typing_extensions import TypeGuard, get_args + +import sniffio + +from .._types import Omit, NotGiven, FileTypes, ArrayFormat, HeadersLike + +_T = TypeVar("_T") +_TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) +_MappingT = TypeVar("_MappingT", bound=Mapping[str, object]) +_SequenceT = TypeVar("_SequenceT", bound=Sequence[object]) +CallableT = TypeVar("CallableT", bound=Callable[..., Any]) + + +def flatten(t: Iterable[Iterable[_T]]) -> list[_T]: + return [item for sublist in t for item in sublist] + + +def extract_files( + # TODO: this needs to take Dict but variance issues..... + # create protocol type ? + query: Mapping[str, object], + *, + paths: Sequence[Sequence[str]], + array_format: ArrayFormat = "brackets", +) -> list[tuple[str, FileTypes]]: + """Recursively extract files from the given dictionary based on specified paths. + + A path may look like this ['foo', 'files', '', 'data']. + + ``array_format`` controls how ```` segments contribute to the emitted + field name. Supported values: ``"brackets"`` (``foo[]``), ``"repeat"`` and + ``"comma"`` (``foo``), ``"indices"`` (``foo[0]``, ``foo[1]``). + + Note: this mutates the given dictionary. + """ + files: list[tuple[str, FileTypes]] = [] + for path in paths: + files.extend(_extract_items(query, path, index=0, flattened_key=None, array_format=array_format)) + return files + + +def _array_suffix(array_format: ArrayFormat, array_index: int) -> str: + if array_format == "brackets": + return "[]" + if array_format == "indices": + return f"[{array_index}]" + if array_format == "repeat" or array_format == "comma": + # Both repeat the bare field name for each file part; there is no + # meaningful way to comma-join binary parts. + return "" + raise NotImplementedError( + f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}" + ) + + +def _extract_items( + obj: object, + path: Sequence[str], + *, + index: int, + flattened_key: str | None, + array_format: ArrayFormat, +) -> list[tuple[str, FileTypes]]: + try: + key = path[index] + except IndexError: + if not is_given(obj): + # no value was provided - we can safely ignore + return [] + + # cyclical import + from .._files import assert_is_file_content + + # We have exhausted the path, return the entry we found. + assert flattened_key is not None + + if is_list(obj): + files: list[tuple[str, FileTypes]] = [] + for array_index, entry in enumerate(obj): + suffix = _array_suffix(array_format, array_index) + emitted_key = (flattened_key + suffix) if flattened_key else suffix + assert_is_file_content(entry, key=emitted_key) + files.append((emitted_key, cast(FileTypes, entry))) + return files + + assert_is_file_content(obj, key=flattened_key) + return [(flattened_key, cast(FileTypes, obj))] + + index += 1 + if is_dict(obj): + try: + # Remove the field if there are no more dict keys in the path, + # only "" traversal markers or end. + if all(p == "" for p in path[index:]): + item = obj.pop(key) + else: + item = obj[key] + except KeyError: + # Key was not present in the dictionary, this is not indicative of an error + # as the given path may not point to a required field. We also do not want + # to enforce required fields as the API may differ from the spec in some cases. + return [] + if flattened_key is None: + flattened_key = key + else: + flattened_key += f"[{key}]" + return _extract_items( + item, + path, + index=index, + flattened_key=flattened_key, + array_format=array_format, + ) + elif is_list(obj): + if key != "": + return [] + + return flatten( + [ + _extract_items( + item, + path, + index=index, + flattened_key=( + (flattened_key if flattened_key is not None else "") + _array_suffix(array_format, array_index) + ), + array_format=array_format, + ) + for array_index, item in enumerate(obj) + ] + ) + + # Something unexpected was passed, just ignore it. + return [] + + +def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]: + return not isinstance(obj, NotGiven) and not isinstance(obj, Omit) + + +# Type safe methods for narrowing types with TypeVars. +# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown], +# however this cause Pyright to rightfully report errors. As we know we don't +# care about the contained types we can safely use `object` in its place. +# +# There are two separate functions defined, `is_*` and `is_*_t` for different use cases. +# `is_*` is for when you're dealing with an unknown input +# `is_*_t` is for when you're narrowing a known union type to a specific subset + + +def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]: + return isinstance(obj, tuple) + + +def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]: + return isinstance(obj, tuple) + + +def is_sequence(obj: object) -> TypeGuard[Sequence[object]]: + return isinstance(obj, Sequence) + + +def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]: + return isinstance(obj, Sequence) + + +def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]: + return isinstance(obj, Mapping) + + +def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]: + return isinstance(obj, Mapping) + + +def is_dict(obj: object) -> TypeGuard[dict[object, object]]: + return isinstance(obj, dict) + + +def is_list(obj: object) -> TypeGuard[list[object]]: + return isinstance(obj, list) + + +def is_iterable(obj: object) -> TypeGuard[Iterable[object]]: + return isinstance(obj, Iterable) + + +# copied from https://github.com/Rapptz/RoboDanny +def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str: + size = len(seq) + if size == 0: + return "" + + if size == 1: + return seq[0] + + if size == 2: + return f"{seq[0]} {final} {seq[1]}" + + return delim.join(seq[:-1]) + f" {final} {seq[-1]}" + + +def quote(string: str) -> str: + """Add single quotation marks around the given string. Does *not* do any escaping.""" + return f"'{string}'" + + +def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: + """Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function. + + Useful for enforcing runtime validation of overloaded functions. + + Example usage: + ```py + @overload + def foo(*, a: str) -> str: ... + + + @overload + def foo(*, b: bool) -> str: ... + + + # This enforces the same constraints that a static type checker would + # i.e. that either a or b must be passed to the function + @required_args(["a"], ["b"]) + def foo(*, a: str | None = None, b: bool | None = None) -> str: ... + ``` + """ + + def inner(func: CallableT) -> CallableT: + params = inspect.signature(func).parameters + positional = [ + name + for name, param in params.items() + if param.kind + in { + param.POSITIONAL_ONLY, + param.POSITIONAL_OR_KEYWORD, + } + ] + + @functools.wraps(func) + def wrapper(*args: object, **kwargs: object) -> object: + given_params: set[str] = set() + for i, _ in enumerate(args): + try: + given_params.add(positional[i]) + except IndexError: + raise TypeError( + f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given" + ) from None + + for key in kwargs.keys(): + given_params.add(key) + + for variant in variants: + matches = all((param in given_params for param in variant)) + if matches: + break + else: # no break + if len(variants) > 1: + variations = human_join( + ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants] + ) + msg = f"Missing required arguments; Expected either {variations} arguments to be given" + else: + assert len(variants) > 0 + + # TODO: this error message is not deterministic + missing = list(set(variants[0]) - given_params) + if len(missing) > 1: + msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}" + else: + msg = f"Missing required argument: {quote(missing[0])}" + raise TypeError(msg) + return func(*args, **kwargs) + + return wrapper # type: ignore + + return inner + + +_K = TypeVar("_K") +_V = TypeVar("_V") + + +@overload +def strip_not_given(obj: None) -> None: ... + + +@overload +def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ... + + +@overload +def strip_not_given(obj: object) -> object: ... + + +def strip_not_given(obj: object | None) -> object: + """Remove all top-level keys where their values are instances of `NotGiven`""" + if obj is None: + return None + + if not is_mapping(obj): + return obj + + return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)} + + +def coerce_integer(val: str) -> int: + return int(val, base=10) + + +def coerce_float(val: str) -> float: + return float(val) + + +def coerce_boolean(val: str) -> bool: + return val == "true" or val == "1" or val == "on" + + +def maybe_coerce_integer(val: str | None) -> int | None: + if val is None: + return None + return coerce_integer(val) + + +def maybe_coerce_float(val: str | None) -> float | None: + if val is None: + return None + return coerce_float(val) + + +def maybe_coerce_boolean(val: str | None) -> bool | None: + if val is None: + return None + return coerce_boolean(val) + + +def removeprefix(string: str, prefix: str) -> str: + """Remove a prefix from a string. + + Backport of `str.removeprefix` for Python < 3.9 + """ + if string.startswith(prefix): + return string[len(prefix) :] + return string + + +def removesuffix(string: str, suffix: str) -> str: + """Remove a suffix from a string. + + Backport of `str.removesuffix` for Python < 3.9 + """ + if string.endswith(suffix): + return string[: -len(suffix)] + return string + + +def file_from_path(path: str) -> FileTypes: + contents = Path(path).read_bytes() + file_name = os.path.basename(path) + return (file_name, contents) + + +def get_required_header(headers: HeadersLike, header: str) -> str: + lower_header = header.lower() + if is_mapping_t(headers): + # mypy doesn't understand the type narrowing here + for k, v in headers.items(): # type: ignore + if k.lower() == lower_header and isinstance(v, str): + return v + + # to deal with the case where the header looks like Stainless-Event-Id + intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize()) + + for normalized_header in [header, lower_header, header.upper(), intercaps_header]: + value = headers.get(normalized_header) + if value: + return value + + raise ValueError(f"Could not find {header} header") + + +def get_async_library() -> str: + try: + return sniffio.current_async_library() + except Exception: + return "false" + + +def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]: + """A version of functools.lru_cache that retains the type signature + for the wrapped function arguments. + """ + wrapper = functools.lru_cache( # noqa: TID251 + maxsize=maxsize, + ) + return cast(Any, wrapper) # type: ignore[no-any-return] + + +def json_safe(data: object) -> object: + """Translates a mapping / sequence recursively in the same fashion + as `pydantic` v2's `model_dump(mode="json")`. + """ + if is_mapping(data): + return {json_safe(key): json_safe(value) for key, value in data.items()} + + if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)): + return [json_safe(item) for item in data] + + if isinstance(data, (datetime, date)): + return data.isoformat() + + return data diff --git a/src/courier/_version.py b/src/courier/_version.py new file mode 100644 index 00000000..f8940809 --- /dev/null +++ b/src/courier/_version.py @@ -0,0 +1,4 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +__title__ = "courier" +__version__ = "7.26.0" # x-release-please-version diff --git a/src/courier/lib/.keep b/src/courier/lib/.keep new file mode 100644 index 00000000..5e2c99fd --- /dev/null +++ b/src/courier/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/src/courier/py.typed b/src/courier/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/src/courier/resources/__init__.py b/src/courier/resources/__init__.py new file mode 100644 index 00000000..036149d7 --- /dev/null +++ b/src/courier/resources/__init__.py @@ -0,0 +1,299 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .auth import ( + AuthResource, + AsyncAuthResource, + AuthResourceWithRawResponse, + AsyncAuthResourceWithRawResponse, + AuthResourceWithStreamingResponse, + AsyncAuthResourceWithStreamingResponse, +) +from .send import ( + SendResource, + AsyncSendResource, + SendResourceWithRawResponse, + AsyncSendResourceWithRawResponse, + SendResourceWithStreamingResponse, + AsyncSendResourceWithStreamingResponse, +) +from .lists import ( + ListsResource, + AsyncListsResource, + ListsResourceWithRawResponse, + AsyncListsResourceWithRawResponse, + ListsResourceWithStreamingResponse, + AsyncListsResourceWithStreamingResponse, +) +from .users import ( + UsersResource, + AsyncUsersResource, + UsersResourceWithRawResponse, + AsyncUsersResourceWithRawResponse, + UsersResourceWithStreamingResponse, + AsyncUsersResourceWithStreamingResponse, +) +from .brands import ( + BrandsResource, + AsyncBrandsResource, + BrandsResourceWithRawResponse, + AsyncBrandsResourceWithRawResponse, + BrandsResourceWithStreamingResponse, + AsyncBrandsResourceWithStreamingResponse, +) +from .digests import ( + DigestsResource, + AsyncDigestsResource, + DigestsResourceWithRawResponse, + AsyncDigestsResourceWithRawResponse, + DigestsResourceWithStreamingResponse, + AsyncDigestsResourceWithStreamingResponse, +) +from .inbound import ( + InboundResource, + AsyncInboundResource, + InboundResourceWithRawResponse, + AsyncInboundResourceWithRawResponse, + InboundResourceWithStreamingResponse, + AsyncInboundResourceWithStreamingResponse, +) +from .tenants import ( + TenantsResource, + AsyncTenantsResource, + TenantsResourceWithRawResponse, + AsyncTenantsResourceWithRawResponse, + TenantsResourceWithStreamingResponse, + AsyncTenantsResourceWithStreamingResponse, +) +from .journeys import ( + JourneysResource, + AsyncJourneysResource, + JourneysResourceWithRawResponse, + AsyncJourneysResourceWithRawResponse, + JourneysResourceWithStreamingResponse, + AsyncJourneysResourceWithStreamingResponse, +) +from .messages import ( + MessagesResource, + AsyncMessagesResource, + MessagesResourceWithRawResponse, + AsyncMessagesResourceWithRawResponse, + MessagesResourceWithStreamingResponse, + AsyncMessagesResourceWithStreamingResponse, +) +from .profiles import ( + ProfilesResource, + AsyncProfilesResource, + ProfilesResourceWithRawResponse, + AsyncProfilesResourceWithRawResponse, + ProfilesResourceWithStreamingResponse, + AsyncProfilesResourceWithStreamingResponse, +) +from .requests import ( + RequestsResource, + AsyncRequestsResource, + RequestsResourceWithRawResponse, + AsyncRequestsResourceWithRawResponse, + RequestsResourceWithStreamingResponse, + AsyncRequestsResourceWithStreamingResponse, +) +from .audiences import ( + AudiencesResource, + AsyncAudiencesResource, + AudiencesResourceWithRawResponse, + AsyncAudiencesResourceWithRawResponse, + AudiencesResourceWithStreamingResponse, + AsyncAudiencesResourceWithStreamingResponse, +) +from .providers import ( + ProvidersResource, + AsyncProvidersResource, + ProvidersResourceWithRawResponse, + AsyncProvidersResourceWithRawResponse, + ProvidersResourceWithStreamingResponse, + AsyncProvidersResourceWithStreamingResponse, +) +from .broadcasts import ( + BroadcastsResource, + AsyncBroadcastsResource, + BroadcastsResourceWithRawResponse, + AsyncBroadcastsResourceWithRawResponse, + BroadcastsResourceWithStreamingResponse, + AsyncBroadcastsResourceWithStreamingResponse, +) +from .automations import ( + AutomationsResource, + AsyncAutomationsResource, + AutomationsResourceWithRawResponse, + AsyncAutomationsResourceWithRawResponse, + AutomationsResourceWithStreamingResponse, + AsyncAutomationsResourceWithStreamingResponse, +) +from .audit_events import ( + AuditEventsResource, + AsyncAuditEventsResource, + AuditEventsResourceWithRawResponse, + AsyncAuditEventsResourceWithRawResponse, + AuditEventsResourceWithStreamingResponse, + AsyncAuditEventsResourceWithStreamingResponse, +) +from .translations import ( + TranslationsResource, + AsyncTranslationsResource, + TranslationsResourceWithRawResponse, + AsyncTranslationsResourceWithRawResponse, + TranslationsResourceWithStreamingResponse, + AsyncTranslationsResourceWithStreamingResponse, +) +from .notifications import ( + NotificationsResource, + AsyncNotificationsResource, + NotificationsResourceWithRawResponse, + AsyncNotificationsResourceWithRawResponse, + NotificationsResourceWithStreamingResponse, + AsyncNotificationsResourceWithStreamingResponse, +) +from .routing_strategies import ( + RoutingStrategiesResource, + AsyncRoutingStrategiesResource, + RoutingStrategiesResourceWithRawResponse, + AsyncRoutingStrategiesResourceWithRawResponse, + RoutingStrategiesResourceWithStreamingResponse, + AsyncRoutingStrategiesResourceWithStreamingResponse, +) +from .workspace_preferences import ( + WorkspacePreferencesResource, + AsyncWorkspacePreferencesResource, + WorkspacePreferencesResourceWithRawResponse, + AsyncWorkspacePreferencesResourceWithRawResponse, + WorkspacePreferencesResourceWithStreamingResponse, + AsyncWorkspacePreferencesResourceWithStreamingResponse, +) + +__all__ = [ + "SendResource", + "AsyncSendResource", + "SendResourceWithRawResponse", + "AsyncSendResourceWithRawResponse", + "SendResourceWithStreamingResponse", + "AsyncSendResourceWithStreamingResponse", + "AudiencesResource", + "AsyncAudiencesResource", + "AudiencesResourceWithRawResponse", + "AsyncAudiencesResourceWithRawResponse", + "AudiencesResourceWithStreamingResponse", + "AsyncAudiencesResourceWithStreamingResponse", + "ProvidersResource", + "AsyncProvidersResource", + "ProvidersResourceWithRawResponse", + "AsyncProvidersResourceWithRawResponse", + "ProvidersResourceWithStreamingResponse", + "AsyncProvidersResourceWithStreamingResponse", + "AuditEventsResource", + "AsyncAuditEventsResource", + "AuditEventsResourceWithRawResponse", + "AsyncAuditEventsResourceWithRawResponse", + "AuditEventsResourceWithStreamingResponse", + "AsyncAuditEventsResourceWithStreamingResponse", + "AuthResource", + "AsyncAuthResource", + "AuthResourceWithRawResponse", + "AsyncAuthResourceWithRawResponse", + "AuthResourceWithStreamingResponse", + "AsyncAuthResourceWithStreamingResponse", + "AutomationsResource", + "AsyncAutomationsResource", + "AutomationsResourceWithRawResponse", + "AsyncAutomationsResourceWithRawResponse", + "AutomationsResourceWithStreamingResponse", + "AsyncAutomationsResourceWithStreamingResponse", + "JourneysResource", + "AsyncJourneysResource", + "JourneysResourceWithRawResponse", + "AsyncJourneysResourceWithRawResponse", + "JourneysResourceWithStreamingResponse", + "AsyncJourneysResourceWithStreamingResponse", + "BroadcastsResource", + "AsyncBroadcastsResource", + "BroadcastsResourceWithRawResponse", + "AsyncBroadcastsResourceWithRawResponse", + "BroadcastsResourceWithStreamingResponse", + "AsyncBroadcastsResourceWithStreamingResponse", + "BrandsResource", + "AsyncBrandsResource", + "BrandsResourceWithRawResponse", + "AsyncBrandsResourceWithRawResponse", + "BrandsResourceWithStreamingResponse", + "AsyncBrandsResourceWithStreamingResponse", + "DigestsResource", + "AsyncDigestsResource", + "DigestsResourceWithRawResponse", + "AsyncDigestsResourceWithRawResponse", + "DigestsResourceWithStreamingResponse", + "AsyncDigestsResourceWithStreamingResponse", + "InboundResource", + "AsyncInboundResource", + "InboundResourceWithRawResponse", + "AsyncInboundResourceWithRawResponse", + "InboundResourceWithStreamingResponse", + "AsyncInboundResourceWithStreamingResponse", + "ListsResource", + "AsyncListsResource", + "ListsResourceWithRawResponse", + "AsyncListsResourceWithRawResponse", + "ListsResourceWithStreamingResponse", + "AsyncListsResourceWithStreamingResponse", + "MessagesResource", + "AsyncMessagesResource", + "MessagesResourceWithRawResponse", + "AsyncMessagesResourceWithRawResponse", + "MessagesResourceWithStreamingResponse", + "AsyncMessagesResourceWithStreamingResponse", + "RequestsResource", + "AsyncRequestsResource", + "RequestsResourceWithRawResponse", + "AsyncRequestsResourceWithRawResponse", + "RequestsResourceWithStreamingResponse", + "AsyncRequestsResourceWithStreamingResponse", + "NotificationsResource", + "AsyncNotificationsResource", + "NotificationsResourceWithRawResponse", + "AsyncNotificationsResourceWithRawResponse", + "NotificationsResourceWithStreamingResponse", + "AsyncNotificationsResourceWithStreamingResponse", + "RoutingStrategiesResource", + "AsyncRoutingStrategiesResource", + "RoutingStrategiesResourceWithRawResponse", + "AsyncRoutingStrategiesResourceWithRawResponse", + "RoutingStrategiesResourceWithStreamingResponse", + "AsyncRoutingStrategiesResourceWithStreamingResponse", + "WorkspacePreferencesResource", + "AsyncWorkspacePreferencesResource", + "WorkspacePreferencesResourceWithRawResponse", + "AsyncWorkspacePreferencesResourceWithRawResponse", + "WorkspacePreferencesResourceWithStreamingResponse", + "AsyncWorkspacePreferencesResourceWithStreamingResponse", + "ProfilesResource", + "AsyncProfilesResource", + "ProfilesResourceWithRawResponse", + "AsyncProfilesResourceWithRawResponse", + "ProfilesResourceWithStreamingResponse", + "AsyncProfilesResourceWithStreamingResponse", + "TenantsResource", + "AsyncTenantsResource", + "TenantsResourceWithRawResponse", + "AsyncTenantsResourceWithRawResponse", + "TenantsResourceWithStreamingResponse", + "AsyncTenantsResourceWithStreamingResponse", + "TranslationsResource", + "AsyncTranslationsResource", + "TranslationsResourceWithRawResponse", + "AsyncTranslationsResourceWithRawResponse", + "TranslationsResourceWithStreamingResponse", + "AsyncTranslationsResourceWithStreamingResponse", + "UsersResource", + "AsyncUsersResource", + "UsersResourceWithRawResponse", + "AsyncUsersResourceWithRawResponse", + "UsersResourceWithStreamingResponse", + "AsyncUsersResourceWithStreamingResponse", +] diff --git a/src/courier/resources/audiences.py b/src/courier/resources/audiences.py new file mode 100644 index 00000000..9a2c2ad7 --- /dev/null +++ b/src/courier/resources/audiences.py @@ -0,0 +1,578 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal + +import httpx + +from ..types import audience_list_params, audience_update_params, audience_list_members_params +from .._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.audience import Audience +from ..types.audience_list_response import AudienceListResponse +from ..types.audience_update_response import AudienceUpdateResponse +from ..types.audience_list_members_response import AudienceListMembersResponse +from ..types.shared_params.audience_filter_config import AudienceFilterConfig + +__all__ = ["AudiencesResource", "AsyncAudiencesResource"] + + +class AudiencesResource(SyncAPIResource): + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + + @cached_property + def with_raw_response(self) -> AudiencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AudiencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AudiencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AudiencesResourceWithStreamingResponse(self) + + def retrieve( + self, + audience_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Audience: + """ + Returns one audience with its name, description, and the filter and AND or OR + operator that decide which users belong to it. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + return self._get( + path_template("/audiences/{audience_id}", audience_id=audience_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Audience, + ) + + def update( + self, + audience_id: str, + *, + description: Optional[str] | Omit = omit, + filter: Optional[AudienceFilterConfig] | Omit = omit, + name: Optional[str] | Omit = omit, + operator: Optional[Literal["AND", "OR"]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AudienceUpdateResponse: + """ + Creates or replaces an audience from a filter and an AND or OR operator. + Membership recalculates automatically as profiles change. + + Args: + description: A description of the audience + + filter: Filter configuration for audience membership containing an array of filter rules + + name: The name of the audience + + operator: The logical operator (AND/OR) combining the top-level `filter.filters`. + Convenience alias for `filter.operator`: if set, it is applied to the top-level + filter group. Prefer setting `operator` directly inside `filter`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + return self._put( + path_template("/audiences/{audience_id}", audience_id=audience_id), + body=maybe_transform( + { + "description": description, + "filter": filter, + "name": name, + "operator": operator, + }, + audience_update_params.AudienceUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AudienceUpdateResponse, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AudienceListResponse: + """Returns the audiences in the workspace with paging. + + Audiences are filter-based + groups that recalculate as user profiles change. + + Args: + cursor: A unique identifier that allows for fetching the next set of audiences + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/audiences", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, audience_list_params.AudienceListParams), + ), + cast_to=AudienceListResponse, + ) + + def delete( + self, + audience_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Deletes an audience permanently, so update any caller sending to it by audience + id first. Those sends fail once the audience is gone. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/audiences/{audience_id}", audience_id=audience_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def list_members( + self, + audience_id: str, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AudienceListMembersResponse: + """Returns the users currently matching an audience filter, with paging. + + Membership + is recalculated, so results shift as profiles change. + + Args: + cursor: A unique identifier that allows for fetching the next set of members + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + return self._get( + path_template("/audiences/{audience_id}/members", audience_id=audience_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, audience_list_members_params.AudienceListMembersParams), + ), + cast_to=AudienceListMembersResponse, + ) + + +class AsyncAudiencesResource(AsyncAPIResource): + """ + Define filter-based groups whose membership Courier recalculates as user profiles change. + """ + + @cached_property + def with_raw_response(self) -> AsyncAudiencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncAudiencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAudiencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncAudiencesResourceWithStreamingResponse(self) + + async def retrieve( + self, + audience_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Audience: + """ + Returns one audience with its name, description, and the filter and AND or OR + operator that decide which users belong to it. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + return await self._get( + path_template("/audiences/{audience_id}", audience_id=audience_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Audience, + ) + + async def update( + self, + audience_id: str, + *, + description: Optional[str] | Omit = omit, + filter: Optional[AudienceFilterConfig] | Omit = omit, + name: Optional[str] | Omit = omit, + operator: Optional[Literal["AND", "OR"]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AudienceUpdateResponse: + """ + Creates or replaces an audience from a filter and an AND or OR operator. + Membership recalculates automatically as profiles change. + + Args: + description: A description of the audience + + filter: Filter configuration for audience membership containing an array of filter rules + + name: The name of the audience + + operator: The logical operator (AND/OR) combining the top-level `filter.filters`. + Convenience alias for `filter.operator`: if set, it is applied to the top-level + filter group. Prefer setting `operator` directly inside `filter`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + return await self._put( + path_template("/audiences/{audience_id}", audience_id=audience_id), + body=await async_maybe_transform( + { + "description": description, + "filter": filter, + "name": name, + "operator": operator, + }, + audience_update_params.AudienceUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AudienceUpdateResponse, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AudienceListResponse: + """Returns the audiences in the workspace with paging. + + Audiences are filter-based + groups that recalculate as user profiles change. + + Args: + cursor: A unique identifier that allows for fetching the next set of audiences + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/audiences", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"cursor": cursor}, audience_list_params.AudienceListParams), + ), + cast_to=AudienceListResponse, + ) + + async def delete( + self, + audience_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Deletes an audience permanently, so update any caller sending to it by audience + id first. Those sends fail once the audience is gone. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/audiences/{audience_id}", audience_id=audience_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def list_members( + self, + audience_id: str, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AudienceListMembersResponse: + """Returns the users currently matching an audience filter, with paging. + + Membership + is recalculated, so results shift as profiles change. + + Args: + cursor: A unique identifier that allows for fetching the next set of members + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audience_id: + raise ValueError(f"Expected a non-empty value for `audience_id` but received {audience_id!r}") + return await self._get( + path_template("/audiences/{audience_id}/members", audience_id=audience_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"cursor": cursor}, audience_list_members_params.AudienceListMembersParams + ), + ), + cast_to=AudienceListMembersResponse, + ) + + +class AudiencesResourceWithRawResponse: + def __init__(self, audiences: AudiencesResource) -> None: + self._audiences = audiences + + self.retrieve = to_raw_response_wrapper( + audiences.retrieve, + ) + self.update = to_raw_response_wrapper( + audiences.update, + ) + self.list = to_raw_response_wrapper( + audiences.list, + ) + self.delete = to_raw_response_wrapper( + audiences.delete, + ) + self.list_members = to_raw_response_wrapper( + audiences.list_members, + ) + + +class AsyncAudiencesResourceWithRawResponse: + def __init__(self, audiences: AsyncAudiencesResource) -> None: + self._audiences = audiences + + self.retrieve = async_to_raw_response_wrapper( + audiences.retrieve, + ) + self.update = async_to_raw_response_wrapper( + audiences.update, + ) + self.list = async_to_raw_response_wrapper( + audiences.list, + ) + self.delete = async_to_raw_response_wrapper( + audiences.delete, + ) + self.list_members = async_to_raw_response_wrapper( + audiences.list_members, + ) + + +class AudiencesResourceWithStreamingResponse: + def __init__(self, audiences: AudiencesResource) -> None: + self._audiences = audiences + + self.retrieve = to_streamed_response_wrapper( + audiences.retrieve, + ) + self.update = to_streamed_response_wrapper( + audiences.update, + ) + self.list = to_streamed_response_wrapper( + audiences.list, + ) + self.delete = to_streamed_response_wrapper( + audiences.delete, + ) + self.list_members = to_streamed_response_wrapper( + audiences.list_members, + ) + + +class AsyncAudiencesResourceWithStreamingResponse: + def __init__(self, audiences: AsyncAudiencesResource) -> None: + self._audiences = audiences + + self.retrieve = async_to_streamed_response_wrapper( + audiences.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + audiences.update, + ) + self.list = async_to_streamed_response_wrapper( + audiences.list, + ) + self.delete = async_to_streamed_response_wrapper( + audiences.delete, + ) + self.list_members = async_to_streamed_response_wrapper( + audiences.list_members, + ) diff --git a/src/courier/resources/audit_events.py b/src/courier/resources/audit_events.py new file mode 100644 index 00000000..042d4b2e --- /dev/null +++ b/src/courier/resources/audit_events.py @@ -0,0 +1,264 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +import httpx + +from ..types import audit_event_list_params +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.audit_event import AuditEvent +from ..types.audit_event_list_response import AuditEventListResponse + +__all__ = ["AuditEventsResource", "AsyncAuditEventsResource"] + + +class AuditEventsResource(SyncAPIResource): + """Read the audit trail of configuration and access changes in your workspace.""" + + @cached_property + def with_raw_response(self) -> AuditEventsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AuditEventsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AuditEventsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AuditEventsResourceWithStreamingResponse(self) + + def retrieve( + self, + audit_event_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AuditEvent: + """ + Returns one audit event by id, including the actor who performed it, the target + they changed, the source, the event type, and a timestamp. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audit_event_id: + raise ValueError(f"Expected a non-empty value for `audit_event_id` but received {audit_event_id!r}") + return self._get( + path_template("/audit-events/{audit_event_id}", audit_event_id=audit_event_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AuditEvent, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AuditEventListResponse: + """Returns the workspace's audit event log with cursor paging. + + Each event records + the actor, target, source, type, and timestamp of a change. + + Args: + cursor: A unique identifier that allows for fetching the next set of audit events. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/audit-events", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, audit_event_list_params.AuditEventListParams), + ), + cast_to=AuditEventListResponse, + ) + + +class AsyncAuditEventsResource(AsyncAPIResource): + """Read the audit trail of configuration and access changes in your workspace.""" + + @cached_property + def with_raw_response(self) -> AsyncAuditEventsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncAuditEventsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAuditEventsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncAuditEventsResourceWithStreamingResponse(self) + + async def retrieve( + self, + audit_event_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AuditEvent: + """ + Returns one audit event by id, including the actor who performed it, the target + they changed, the source, the event type, and a timestamp. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not audit_event_id: + raise ValueError(f"Expected a non-empty value for `audit_event_id` but received {audit_event_id!r}") + return await self._get( + path_template("/audit-events/{audit_event_id}", audit_event_id=audit_event_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AuditEvent, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AuditEventListResponse: + """Returns the workspace's audit event log with cursor paging. + + Each event records + the actor, target, source, type, and timestamp of a change. + + Args: + cursor: A unique identifier that allows for fetching the next set of audit events. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/audit-events", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"cursor": cursor}, audit_event_list_params.AuditEventListParams), + ), + cast_to=AuditEventListResponse, + ) + + +class AuditEventsResourceWithRawResponse: + def __init__(self, audit_events: AuditEventsResource) -> None: + self._audit_events = audit_events + + self.retrieve = to_raw_response_wrapper( + audit_events.retrieve, + ) + self.list = to_raw_response_wrapper( + audit_events.list, + ) + + +class AsyncAuditEventsResourceWithRawResponse: + def __init__(self, audit_events: AsyncAuditEventsResource) -> None: + self._audit_events = audit_events + + self.retrieve = async_to_raw_response_wrapper( + audit_events.retrieve, + ) + self.list = async_to_raw_response_wrapper( + audit_events.list, + ) + + +class AuditEventsResourceWithStreamingResponse: + def __init__(self, audit_events: AuditEventsResource) -> None: + self._audit_events = audit_events + + self.retrieve = to_streamed_response_wrapper( + audit_events.retrieve, + ) + self.list = to_streamed_response_wrapper( + audit_events.list, + ) + + +class AsyncAuditEventsResourceWithStreamingResponse: + def __init__(self, audit_events: AsyncAuditEventsResource) -> None: + self._audit_events = audit_events + + self.retrieve = async_to_streamed_response_wrapper( + audit_events.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + audit_events.list, + ) diff --git a/src/courier/resources/auth.py b/src/courier/resources/auth.py new file mode 100644 index 00000000..c3e17fcc --- /dev/null +++ b/src/courier/resources/auth.py @@ -0,0 +1,249 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ..types import auth_issue_token_params +from .._types import Body, Query, Headers, NotGiven, not_given +from .._utils import maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.auth_issue_token_response import AuthIssueTokenResponse + +__all__ = ["AuthResource", "AsyncAuthResource"] + + +class AuthResource(SyncAPIResource): + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + + @cached_property + def with_raw_response(self) -> AuthResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AuthResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AuthResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AuthResourceWithStreamingResponse(self) + + def issue_token( + self, + *, + expires_in: str, + scope: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AuthIssueTokenResponse: + """Returns a JWT for authenticating client-side SDKs such as the Inbox. + + You supply + the scope and an expires_in duration, both required. + + Args: + expires_in: + Duration for token expiration. Accepts various time formats: + + - "2 hours" - 2 hours from now + - "1d" - 1 day + - "3 days" - 3 days + - "10h" - 10 hours + - "2.5 hrs" - 2.5 hours + - "1m" - 1 minute + - "5s" - 5 seconds + - "1y" - 1 year + + scope: + Available scopes: + + - `user_id:` - Defines which user the token will be scoped to. Multiple + can be listed if needed. Ex `user_id:pigeon user_id:bluebird`. + - `read:messages` - Read messages. + - `read:user-tokens` - Read user push tokens. + - `write:user-tokens` - Write user push tokens. + - `read:brands[:]` - Read brands, optionally restricted to a specific + brand_id. Examples `read:brands`, `read:brands:my_brand`. + - `write:brands[:]` - Write brands, optionally restricted to a + specific brand_id. Examples `write:brands`, `write:brands:my_brand`. + - `inbox:read:messages` - Read inbox messages. + - `inbox:write:events` - Write inbox events, such as mark message as read. + - `read:preferences` - Read user preferences. + - `write:preferences` - Write user preferences. Example: + `user_id:user123 write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands` + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/auth/issue-token", + body=maybe_transform( + { + "expires_in": expires_in, + "scope": scope, + }, + auth_issue_token_params.AuthIssueTokenParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AuthIssueTokenResponse, + ) + + +class AsyncAuthResource(AsyncAPIResource): + """ + Issue scoped, short-lived JWTs so client-side SDKs — Inbox, Preferences, and the embedded designer — can call Courier as a single user. Server-side requests authenticate with your workspace API key instead. + """ + + @cached_property + def with_raw_response(self) -> AsyncAuthResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncAuthResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAuthResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncAuthResourceWithStreamingResponse(self) + + async def issue_token( + self, + *, + expires_in: str, + scope: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AuthIssueTokenResponse: + """Returns a JWT for authenticating client-side SDKs such as the Inbox. + + You supply + the scope and an expires_in duration, both required. + + Args: + expires_in: + Duration for token expiration. Accepts various time formats: + + - "2 hours" - 2 hours from now + - "1d" - 1 day + - "3 days" - 3 days + - "10h" - 10 hours + - "2.5 hrs" - 2.5 hours + - "1m" - 1 minute + - "5s" - 5 seconds + - "1y" - 1 year + + scope: + Available scopes: + + - `user_id:` - Defines which user the token will be scoped to. Multiple + can be listed if needed. Ex `user_id:pigeon user_id:bluebird`. + - `read:messages` - Read messages. + - `read:user-tokens` - Read user push tokens. + - `write:user-tokens` - Write user push tokens. + - `read:brands[:]` - Read brands, optionally restricted to a specific + brand_id. Examples `read:brands`, `read:brands:my_brand`. + - `write:brands[:]` - Write brands, optionally restricted to a + specific brand_id. Examples `write:brands`, `write:brands:my_brand`. + - `inbox:read:messages` - Read inbox messages. + - `inbox:write:events` - Write inbox events, such as mark message as read. + - `read:preferences` - Read user preferences. + - `write:preferences` - Write user preferences. Example: + `user_id:user123 write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands` + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/auth/issue-token", + body=await async_maybe_transform( + { + "expires_in": expires_in, + "scope": scope, + }, + auth_issue_token_params.AuthIssueTokenParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AuthIssueTokenResponse, + ) + + +class AuthResourceWithRawResponse: + def __init__(self, auth: AuthResource) -> None: + self._auth = auth + + self.issue_token = to_raw_response_wrapper( + auth.issue_token, + ) + + +class AsyncAuthResourceWithRawResponse: + def __init__(self, auth: AsyncAuthResource) -> None: + self._auth = auth + + self.issue_token = async_to_raw_response_wrapper( + auth.issue_token, + ) + + +class AuthResourceWithStreamingResponse: + def __init__(self, auth: AuthResource) -> None: + self._auth = auth + + self.issue_token = to_streamed_response_wrapper( + auth.issue_token, + ) + + +class AsyncAuthResourceWithStreamingResponse: + def __init__(self, auth: AsyncAuthResource) -> None: + self._auth = auth + + self.issue_token = async_to_streamed_response_wrapper( + auth.issue_token, + ) diff --git a/src/courier/resources/automations/__init__.py b/src/courier/resources/automations/__init__.py new file mode 100644 index 00000000..65960236 --- /dev/null +++ b/src/courier/resources/automations/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .invoke import ( + InvokeResource, + AsyncInvokeResource, + InvokeResourceWithRawResponse, + AsyncInvokeResourceWithRawResponse, + InvokeResourceWithStreamingResponse, + AsyncInvokeResourceWithStreamingResponse, +) +from .automations import ( + AutomationsResource, + AsyncAutomationsResource, + AutomationsResourceWithRawResponse, + AsyncAutomationsResourceWithRawResponse, + AutomationsResourceWithStreamingResponse, + AsyncAutomationsResourceWithStreamingResponse, +) + +__all__ = [ + "InvokeResource", + "AsyncInvokeResource", + "InvokeResourceWithRawResponse", + "AsyncInvokeResourceWithRawResponse", + "InvokeResourceWithStreamingResponse", + "AsyncInvokeResourceWithStreamingResponse", + "AutomationsResource", + "AsyncAutomationsResource", + "AutomationsResourceWithRawResponse", + "AsyncAutomationsResourceWithRawResponse", + "AutomationsResourceWithStreamingResponse", + "AsyncAutomationsResourceWithStreamingResponse", +] diff --git a/src/courier/resources/automations/automations.py b/src/courier/resources/automations/automations.py new file mode 100644 index 00000000..1ae9add2 --- /dev/null +++ b/src/courier/resources/automations/automations.py @@ -0,0 +1,257 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +from .invoke import ( + InvokeResource, + AsyncInvokeResource, + InvokeResourceWithRawResponse, + AsyncInvokeResourceWithRawResponse, + InvokeResourceWithStreamingResponse, + AsyncInvokeResourceWithStreamingResponse, +) +from ...types import automation_list_params +from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from ..._utils import maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.automation_template_list_response import AutomationTemplateListResponse + +__all__ = ["AutomationsResource", "AsyncAutomationsResource"] + + +class AutomationsResource(SyncAPIResource): + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + + @cached_property + def invoke(self) -> InvokeResource: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + return InvokeResource(self._client) + + @cached_property + def with_raw_response(self) -> AutomationsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AutomationsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AutomationsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AutomationsResourceWithStreamingResponse(self) + + def list( + self, + *, + cursor: str | Omit = omit, + version: Literal["published", "draft"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AutomationTemplateListResponse: + """ + Lists the workspace's saved automation templates, each with its id and a cursor + for paging to the next page of results. + + Args: + cursor: A cursor token for pagination. Use the cursor from the previous response to + fetch the next page of results. + + version: The version of templates to retrieve. Accepted values are published (for + published templates) or draft (for draft templates). Defaults to published. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/automations", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "version": version, + }, + automation_list_params.AutomationListParams, + ), + ), + cast_to=AutomationTemplateListResponse, + ) + + +class AsyncAutomationsResource(AsyncAPIResource): + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + + @cached_property + def invoke(self) -> AsyncInvokeResource: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + return AsyncInvokeResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncAutomationsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncAutomationsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAutomationsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncAutomationsResourceWithStreamingResponse(self) + + async def list( + self, + *, + cursor: str | Omit = omit, + version: Literal["published", "draft"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AutomationTemplateListResponse: + """ + Lists the workspace's saved automation templates, each with its id and a cursor + for paging to the next page of results. + + Args: + cursor: A cursor token for pagination. Use the cursor from the previous response to + fetch the next page of results. + + version: The version of templates to retrieve. Accepted values are published (for + published templates) or draft (for draft templates). Defaults to published. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/automations", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "version": version, + }, + automation_list_params.AutomationListParams, + ), + ), + cast_to=AutomationTemplateListResponse, + ) + + +class AutomationsResourceWithRawResponse: + def __init__(self, automations: AutomationsResource) -> None: + self._automations = automations + + self.list = to_raw_response_wrapper( + automations.list, + ) + + @cached_property + def invoke(self) -> InvokeResourceWithRawResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + return InvokeResourceWithRawResponse(self._automations.invoke) + + +class AsyncAutomationsResourceWithRawResponse: + def __init__(self, automations: AsyncAutomationsResource) -> None: + self._automations = automations + + self.list = async_to_raw_response_wrapper( + automations.list, + ) + + @cached_property + def invoke(self) -> AsyncInvokeResourceWithRawResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + return AsyncInvokeResourceWithRawResponse(self._automations.invoke) + + +class AutomationsResourceWithStreamingResponse: + def __init__(self, automations: AutomationsResource) -> None: + self._automations = automations + + self.list = to_streamed_response_wrapper( + automations.list, + ) + + @cached_property + def invoke(self) -> InvokeResourceWithStreamingResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + return InvokeResourceWithStreamingResponse(self._automations.invoke) + + +class AsyncAutomationsResourceWithStreamingResponse: + def __init__(self, automations: AsyncAutomationsResource) -> None: + self._automations = automations + + self.list = async_to_streamed_response_wrapper( + automations.list, + ) + + @cached_property + def invoke(self) -> AsyncInvokeResourceWithStreamingResponse: + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + return AsyncInvokeResourceWithStreamingResponse(self._automations.invoke) diff --git a/src/courier/resources/automations/invoke.py b/src/courier/resources/automations/invoke.py new file mode 100644 index 00000000..c1e9cfe5 --- /dev/null +++ b/src/courier/resources/automations/invoke.py @@ -0,0 +1,359 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional + +import httpx + +from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.automations import invoke_invoke_ad_hoc_params, invoke_invoke_by_template_params +from ...types.automation_invoke_response import AutomationInvokeResponse + +__all__ = ["InvokeResource", "AsyncInvokeResource"] + + +class InvokeResource(SyncAPIResource): + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + + @cached_property + def with_raw_response(self) -> InvokeResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return InvokeResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> InvokeResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return InvokeResourceWithStreamingResponse(self) + + def invoke_ad_hoc( + self, + *, + automation: invoke_invoke_ad_hoc_params.Automation, + brand: Optional[str] | Omit = omit, + data: Optional[Dict[str, object]] | Omit = omit, + profile: Optional[Dict[str, object]] | Omit = omit, + recipient: Optional[str] | Omit = omit, + template: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AutomationInvokeResponse: + """ + Runs a series of automation steps supplied inline, without a saved template, and + returns a runId. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/automations/invoke", + body=maybe_transform( + { + "automation": automation, + "brand": brand, + "data": data, + "profile": profile, + "recipient": recipient, + "template": template, + }, + invoke_invoke_ad_hoc_params.InvokeInvokeAdHocParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AutomationInvokeResponse, + ) + + def invoke_by_template( + self, + template_id: str, + *, + recipient: Optional[str], + brand: Optional[str] | Omit = omit, + data: Optional[Dict[str, object]] | Omit = omit, + profile: Optional[Dict[str, object]] | Omit = omit, + template: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AutomationInvokeResponse: + """ + Starts an automation run from a saved template for one recipient, with optional + data and profile, and returns a runId. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/automations/{template_id}/invoke", template_id=template_id), + body=maybe_transform( + { + "recipient": recipient, + "brand": brand, + "data": data, + "profile": profile, + "template": template, + }, + invoke_invoke_by_template_params.InvokeInvokeByTemplateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AutomationInvokeResponse, + ) + + +class AsyncInvokeResource(AsyncAPIResource): + """ + Invoke a stored automation template or an ad hoc automation defined in the request. + """ + + @cached_property + def with_raw_response(self) -> AsyncInvokeResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncInvokeResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncInvokeResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncInvokeResourceWithStreamingResponse(self) + + async def invoke_ad_hoc( + self, + *, + automation: invoke_invoke_ad_hoc_params.Automation, + brand: Optional[str] | Omit = omit, + data: Optional[Dict[str, object]] | Omit = omit, + profile: Optional[Dict[str, object]] | Omit = omit, + recipient: Optional[str] | Omit = omit, + template: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AutomationInvokeResponse: + """ + Runs a series of automation steps supplied inline, without a saved template, and + returns a runId. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/automations/invoke", + body=await async_maybe_transform( + { + "automation": automation, + "brand": brand, + "data": data, + "profile": profile, + "recipient": recipient, + "template": template, + }, + invoke_invoke_ad_hoc_params.InvokeInvokeAdHocParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AutomationInvokeResponse, + ) + + async def invoke_by_template( + self, + template_id: str, + *, + recipient: Optional[str], + brand: Optional[str] | Omit = omit, + data: Optional[Dict[str, object]] | Omit = omit, + profile: Optional[Dict[str, object]] | Omit = omit, + template: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AutomationInvokeResponse: + """ + Starts an automation run from a saved template for one recipient, with optional + data and profile, and returns a runId. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/automations/{template_id}/invoke", template_id=template_id), + body=await async_maybe_transform( + { + "recipient": recipient, + "brand": brand, + "data": data, + "profile": profile, + "template": template, + }, + invoke_invoke_by_template_params.InvokeInvokeByTemplateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AutomationInvokeResponse, + ) + + +class InvokeResourceWithRawResponse: + def __init__(self, invoke: InvokeResource) -> None: + self._invoke = invoke + + self.invoke_ad_hoc = to_raw_response_wrapper( + invoke.invoke_ad_hoc, + ) + self.invoke_by_template = to_raw_response_wrapper( + invoke.invoke_by_template, + ) + + +class AsyncInvokeResourceWithRawResponse: + def __init__(self, invoke: AsyncInvokeResource) -> None: + self._invoke = invoke + + self.invoke_ad_hoc = async_to_raw_response_wrapper( + invoke.invoke_ad_hoc, + ) + self.invoke_by_template = async_to_raw_response_wrapper( + invoke.invoke_by_template, + ) + + +class InvokeResourceWithStreamingResponse: + def __init__(self, invoke: InvokeResource) -> None: + self._invoke = invoke + + self.invoke_ad_hoc = to_streamed_response_wrapper( + invoke.invoke_ad_hoc, + ) + self.invoke_by_template = to_streamed_response_wrapper( + invoke.invoke_by_template, + ) + + +class AsyncInvokeResourceWithStreamingResponse: + def __init__(self, invoke: AsyncInvokeResource) -> None: + self._invoke = invoke + + self.invoke_ad_hoc = async_to_streamed_response_wrapper( + invoke.invoke_ad_hoc, + ) + self.invoke_by_template = async_to_streamed_response_wrapper( + invoke.invoke_by_template, + ) diff --git a/src/courier/resources/brands.py b/src/courier/resources/brands.py new file mode 100644 index 00000000..ca96b48f --- /dev/null +++ b/src/courier/resources/brands.py @@ -0,0 +1,584 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +import httpx + +from ..types import brand_list_params, brand_create_params, brand_update_params +from .._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from .._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..types.brand import Brand +from .._base_client import make_request_options +from ..types.brand_list_response import BrandListResponse +from ..types.brand_settings_param import BrandSettingsParam +from ..types.brand_snippets_param import BrandSnippetsParam + +__all__ = ["BrandsResource", "AsyncBrandsResource"] + + +class BrandsResource(SyncAPIResource): + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + + @cached_property + def with_raw_response(self) -> BrandsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return BrandsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> BrandsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return BrandsResourceWithStreamingResponse(self) + + def create( + self, + *, + name: str, + settings: BrandSettingsParam, + id: Optional[str] | Omit = omit, + snippets: Optional[BrandSnippetsParam] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Brand: + """Creates a brand from a name and settings, including primary and secondary + colors. + + Brands supply the logo, colors, and styling that templates render with. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/brands", + body=maybe_transform( + { + "name": name, + "settings": settings, + "id": id, + "snippets": snippets, + }, + brand_create_params.BrandCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Brand, + ) + + def retrieve( + self, + brand_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Brand: + """ + Returns one brand by id, including its colors, logo and styling settings, + Handlebars snippets, and published version. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not brand_id: + raise ValueError(f"Expected a non-empty value for `brand_id` but received {brand_id!r}") + return self._get( + path_template("/brands/{brand_id}", brand_id=brand_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Brand, + ) + + def update( + self, + brand_id: str, + *, + name: str, + settings: Optional[BrandSettingsParam] | Omit = omit, + snippets: Optional[BrandSnippetsParam] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Brand: + """ + Replaces a brand with the values you supply, so send the complete settings and + snippets rather than only the fields you want changed. + + Args: + name: The name of the brand. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not brand_id: + raise ValueError(f"Expected a non-empty value for `brand_id` but received {brand_id!r}") + return self._put( + path_template("/brands/{brand_id}", brand_id=brand_id), + body=maybe_transform( + { + "name": name, + "settings": settings, + "snippets": snippets, + }, + brand_update_params.BrandUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Brand, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BrandListResponse: + """Lists the workspace's brands. + + Every entry carries its name, styling settings, + snippets, and published version. + + Args: + cursor: A unique identifier that allows for fetching the next set of brands. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/brands", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, brand_list_params.BrandListParams), + ), + cast_to=BrandListResponse, + ) + + def delete( + self, + brand_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a brand by id. + + Reassign any template or tenant that references it before + deleting to keep their styling intact. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not brand_id: + raise ValueError(f"Expected a non-empty value for `brand_id` but received {brand_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/brands/{brand_id}", brand_id=brand_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncBrandsResource(AsyncAPIResource): + """ + Manage the logos, colors, and layout that give the templates you send a consistent look. + """ + + @cached_property + def with_raw_response(self) -> AsyncBrandsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncBrandsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncBrandsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncBrandsResourceWithStreamingResponse(self) + + async def create( + self, + *, + name: str, + settings: BrandSettingsParam, + id: Optional[str] | Omit = omit, + snippets: Optional[BrandSnippetsParam] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Brand: + """Creates a brand from a name and settings, including primary and secondary + colors. + + Brands supply the logo, colors, and styling that templates render with. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/brands", + body=await async_maybe_transform( + { + "name": name, + "settings": settings, + "id": id, + "snippets": snippets, + }, + brand_create_params.BrandCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Brand, + ) + + async def retrieve( + self, + brand_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Brand: + """ + Returns one brand by id, including its colors, logo and styling settings, + Handlebars snippets, and published version. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not brand_id: + raise ValueError(f"Expected a non-empty value for `brand_id` but received {brand_id!r}") + return await self._get( + path_template("/brands/{brand_id}", brand_id=brand_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Brand, + ) + + async def update( + self, + brand_id: str, + *, + name: str, + settings: Optional[BrandSettingsParam] | Omit = omit, + snippets: Optional[BrandSnippetsParam] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Brand: + """ + Replaces a brand with the values you supply, so send the complete settings and + snippets rather than only the fields you want changed. + + Args: + name: The name of the brand. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not brand_id: + raise ValueError(f"Expected a non-empty value for `brand_id` but received {brand_id!r}") + return await self._put( + path_template("/brands/{brand_id}", brand_id=brand_id), + body=await async_maybe_transform( + { + "name": name, + "settings": settings, + "snippets": snippets, + }, + brand_update_params.BrandUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Brand, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BrandListResponse: + """Lists the workspace's brands. + + Every entry carries its name, styling settings, + snippets, and published version. + + Args: + cursor: A unique identifier that allows for fetching the next set of brands. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/brands", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"cursor": cursor}, brand_list_params.BrandListParams), + ), + cast_to=BrandListResponse, + ) + + async def delete( + self, + brand_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a brand by id. + + Reassign any template or tenant that references it before + deleting to keep their styling intact. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not brand_id: + raise ValueError(f"Expected a non-empty value for `brand_id` but received {brand_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/brands/{brand_id}", brand_id=brand_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class BrandsResourceWithRawResponse: + def __init__(self, brands: BrandsResource) -> None: + self._brands = brands + + self.create = to_raw_response_wrapper( + brands.create, + ) + self.retrieve = to_raw_response_wrapper( + brands.retrieve, + ) + self.update = to_raw_response_wrapper( + brands.update, + ) + self.list = to_raw_response_wrapper( + brands.list, + ) + self.delete = to_raw_response_wrapper( + brands.delete, + ) + + +class AsyncBrandsResourceWithRawResponse: + def __init__(self, brands: AsyncBrandsResource) -> None: + self._brands = brands + + self.create = async_to_raw_response_wrapper( + brands.create, + ) + self.retrieve = async_to_raw_response_wrapper( + brands.retrieve, + ) + self.update = async_to_raw_response_wrapper( + brands.update, + ) + self.list = async_to_raw_response_wrapper( + brands.list, + ) + self.delete = async_to_raw_response_wrapper( + brands.delete, + ) + + +class BrandsResourceWithStreamingResponse: + def __init__(self, brands: BrandsResource) -> None: + self._brands = brands + + self.create = to_streamed_response_wrapper( + brands.create, + ) + self.retrieve = to_streamed_response_wrapper( + brands.retrieve, + ) + self.update = to_streamed_response_wrapper( + brands.update, + ) + self.list = to_streamed_response_wrapper( + brands.list, + ) + self.delete = to_streamed_response_wrapper( + brands.delete, + ) + + +class AsyncBrandsResourceWithStreamingResponse: + def __init__(self, brands: AsyncBrandsResource) -> None: + self._brands = brands + + self.create = async_to_streamed_response_wrapper( + brands.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + brands.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + brands.update, + ) + self.list = async_to_streamed_response_wrapper( + brands.list, + ) + self.delete = async_to_streamed_response_wrapper( + brands.delete, + ) diff --git a/src/courier/resources/broadcasts.py b/src/courier/resources/broadcasts.py new file mode 100644 index 00000000..aa55c886 --- /dev/null +++ b/src/courier/resources/broadcasts.py @@ -0,0 +1,1183 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal + +import httpx + +from ..types import ( + NotificationTemplateState, + broadcast_list_params, + broadcast_send_params, + broadcast_create_params, + broadcast_update_params, + broadcast_schedule_params, + broadcast_put_content_params, + broadcast_retrieve_content_params, +) +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.broadcast import Broadcast +from ..types.broadcast_list_response import BroadcastListResponse +from ..types.notification_template_state import NotificationTemplateState +from ..types.notification_content_get_response import NotificationContentGetResponse +from ..types.notification_content_mutation_response import NotificationContentMutationResponse + +__all__ = ["BroadcastsResource", "AsyncBroadcastsResource"] + + +class BroadcastsResource(SyncAPIResource): + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + + @cached_property + def with_raw_response(self) -> BroadcastsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return BroadcastsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> BroadcastsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return BroadcastsResourceWithStreamingResponse(self) + + def create( + self, + *, + channel: Literal["email", "sms", "push", "inbox", "slack", "msteams"], + name: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Create a broadcast. + + Provisions a private notification template for the broadcast + and returns the new broadcast in the draft state. Exactly one channel is + required. + + Args: + channel: The single delivery channel for this broadcast. + + name: Human-readable name. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/broadcasts", + body=maybe_transform( + { + "channel": channel, + "name": name, + }, + broadcast_create_params.BroadcastCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def retrieve( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Retrieve a broadcast by ID. + + Archived broadcasts return 404. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._get( + path_template("/broadcasts/{broadcast_id}", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def update( + self, + broadcast_id: str, + *, + name: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Update a broadcast's name. + + Content is edited via the broadcast's notification + template, not this endpoint. + + Args: + name: New human-readable name. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._put( + path_template("/broadcasts/{broadcast_id}", broadcast_id=broadcast_id), + body=maybe_transform({"name": name}, broadcast_update_params.BroadcastUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BroadcastListResponse: + """List broadcasts in your workspace. + + Cursor-paginated; returns broadcasts + newest-first. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of results per page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/broadcasts", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + broadcast_list_params.BroadcastListParams, + ), + ), + cast_to=BroadcastListResponse, + ) + + def archive( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Archive a broadcast. + + This is a soft delete — the archived broadcast is returned + and no longer appears in list results. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._delete( + path_template("/broadcasts/{broadcast_id}", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def cancel( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Cancel a broadcast's pending schedule, returning it to the draft state. + + Only + valid for a scheduled broadcast. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._post( + path_template("/broadcasts/{broadcast_id}/cancel", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def duplicate( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """ + Duplicate a broadcast (and its template) into a new draft named "{source name} + (copy)". + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._post( + path_template("/broadcasts/{broadcast_id}/duplicate", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def put_content( + self, + broadcast_id: str, + *, + content: broadcast_put_content_params.Content, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """ + Author the broadcast's content by replacing the draft elemental content of its + private notification template. The draft is published automatically when the + broadcast is sent or scheduled. + + Args: + content: Elemental content payload. The server defaults `version` when omitted. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._put( + path_template("/broadcasts/{broadcast_id}/content", broadcast_id=broadcast_id), + body=maybe_transform( + { + "content": content, + "state": state, + }, + broadcast_put_content_params.BroadcastPutContentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + def retrieve_content( + self, + broadcast_id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentGetResponse: + """ + Retrieve the broadcast's content — the elemental content of its private + notification template. Defaults to the working draft, since broadcast content is + authored as a draft until the broadcast is sent. + + Args: + version: Accepts `draft`, `published`, or a version string (e.g. `v001`). Defaults to + `draft`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._get( + path_template("/broadcasts/{broadcast_id}/content", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"version": version}, broadcast_retrieve_content_params.BroadcastRetrieveContentParams + ), + ), + cast_to=NotificationContentGetResponse, + ) + + def schedule( + self, + broadcast_id: str, + *, + recipient_id: str, + recipient_type: Literal["list", "audience"], + scheduled_to: str, + timezone: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Schedule a broadcast for a future send to a list or audience. + + Publishes the + broadcast template first. Not allowed once the broadcast is sending or sent. For + an immediate send use POST /broadcasts/{broadcastId}/send. + + Args: + recipient_id: ID of the target list or audience. + + recipient_type: Whether the broadcast targets a list or an audience. + + scheduled_to: Wall-clock timestamp of the future send, no timezone offset (e.g. + "2026-07-21T20:00:00"). The zone is given by `timezone`. + + timezone: IANA timezone for the scheduled send (e.g. America/New_York). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._post( + path_template("/broadcasts/{broadcast_id}/schedule", broadcast_id=broadcast_id), + body=maybe_transform( + { + "recipient_id": recipient_id, + "recipient_type": recipient_type, + "scheduled_to": scheduled_to, + "timezone": timezone, + }, + broadcast_schedule_params.BroadcastScheduleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + def send( + self, + broadcast_id: str, + *, + recipient_id: str, + recipient_type: Literal["list", "audience"], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Send a broadcast immediately to a list or audience. + + Publishes the broadcast + template first. Not allowed once the broadcast is sending or sent. + + Args: + recipient_id: ID of the target list or audience. + + recipient_type: Whether the broadcast targets a list or an audience. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return self._post( + path_template("/broadcasts/{broadcast_id}/send", broadcast_id=broadcast_id), + body=maybe_transform( + { + "recipient_id": recipient_id, + "recipient_type": recipient_type, + }, + broadcast_send_params.BroadcastSendParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + +class AsyncBroadcastsResource(AsyncAPIResource): + """ + Create a one-off send to a list or audience, author its content, then send it immediately or schedule it for later. + """ + + @cached_property + def with_raw_response(self) -> AsyncBroadcastsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncBroadcastsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncBroadcastsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncBroadcastsResourceWithStreamingResponse(self) + + async def create( + self, + *, + channel: Literal["email", "sms", "push", "inbox", "slack", "msteams"], + name: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Create a broadcast. + + Provisions a private notification template for the broadcast + and returns the new broadcast in the draft state. Exactly one channel is + required. + + Args: + channel: The single delivery channel for this broadcast. + + name: Human-readable name. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/broadcasts", + body=await async_maybe_transform( + { + "channel": channel, + "name": name, + }, + broadcast_create_params.BroadcastCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def retrieve( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Retrieve a broadcast by ID. + + Archived broadcasts return 404. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._get( + path_template("/broadcasts/{broadcast_id}", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def update( + self, + broadcast_id: str, + *, + name: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Update a broadcast's name. + + Content is edited via the broadcast's notification + template, not this endpoint. + + Args: + name: New human-readable name. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._put( + path_template("/broadcasts/{broadcast_id}", broadcast_id=broadcast_id), + body=await async_maybe_transform({"name": name}, broadcast_update_params.BroadcastUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BroadcastListResponse: + """List broadcasts in your workspace. + + Cursor-paginated; returns broadcasts + newest-first. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of results per page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/broadcasts", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + broadcast_list_params.BroadcastListParams, + ), + ), + cast_to=BroadcastListResponse, + ) + + async def archive( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Archive a broadcast. + + This is a soft delete — the archived broadcast is returned + and no longer appears in list results. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._delete( + path_template("/broadcasts/{broadcast_id}", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def cancel( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Cancel a broadcast's pending schedule, returning it to the draft state. + + Only + valid for a scheduled broadcast. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._post( + path_template("/broadcasts/{broadcast_id}/cancel", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def duplicate( + self, + broadcast_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """ + Duplicate a broadcast (and its template) into a new draft named "{source name} + (copy)". + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._post( + path_template("/broadcasts/{broadcast_id}/duplicate", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def put_content( + self, + broadcast_id: str, + *, + content: broadcast_put_content_params.Content, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """ + Author the broadcast's content by replacing the draft elemental content of its + private notification template. The draft is published automatically when the + broadcast is sent or scheduled. + + Args: + content: Elemental content payload. The server defaults `version` when omitted. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._put( + path_template("/broadcasts/{broadcast_id}/content", broadcast_id=broadcast_id), + body=await async_maybe_transform( + { + "content": content, + "state": state, + }, + broadcast_put_content_params.BroadcastPutContentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + async def retrieve_content( + self, + broadcast_id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentGetResponse: + """ + Retrieve the broadcast's content — the elemental content of its private + notification template. Defaults to the working draft, since broadcast content is + authored as a draft until the broadcast is sent. + + Args: + version: Accepts `draft`, `published`, or a version string (e.g. `v001`). Defaults to + `draft`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._get( + path_template("/broadcasts/{broadcast_id}/content", broadcast_id=broadcast_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"version": version}, broadcast_retrieve_content_params.BroadcastRetrieveContentParams + ), + ), + cast_to=NotificationContentGetResponse, + ) + + async def schedule( + self, + broadcast_id: str, + *, + recipient_id: str, + recipient_type: Literal["list", "audience"], + scheduled_to: str, + timezone: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Schedule a broadcast for a future send to a list or audience. + + Publishes the + broadcast template first. Not allowed once the broadcast is sending or sent. For + an immediate send use POST /broadcasts/{broadcastId}/send. + + Args: + recipient_id: ID of the target list or audience. + + recipient_type: Whether the broadcast targets a list or an audience. + + scheduled_to: Wall-clock timestamp of the future send, no timezone offset (e.g. + "2026-07-21T20:00:00"). The zone is given by `timezone`. + + timezone: IANA timezone for the scheduled send (e.g. America/New_York). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._post( + path_template("/broadcasts/{broadcast_id}/schedule", broadcast_id=broadcast_id), + body=await async_maybe_transform( + { + "recipient_id": recipient_id, + "recipient_type": recipient_type, + "scheduled_to": scheduled_to, + "timezone": timezone, + }, + broadcast_schedule_params.BroadcastScheduleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + async def send( + self, + broadcast_id: str, + *, + recipient_id: str, + recipient_type: Literal["list", "audience"], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Broadcast: + """Send a broadcast immediately to a list or audience. + + Publishes the broadcast + template first. Not allowed once the broadcast is sending or sent. + + Args: + recipient_id: ID of the target list or audience. + + recipient_type: Whether the broadcast targets a list or an audience. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not broadcast_id: + raise ValueError(f"Expected a non-empty value for `broadcast_id` but received {broadcast_id!r}") + return await self._post( + path_template("/broadcasts/{broadcast_id}/send", broadcast_id=broadcast_id), + body=await async_maybe_transform( + { + "recipient_id": recipient_id, + "recipient_type": recipient_type, + }, + broadcast_send_params.BroadcastSendParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Broadcast, + ) + + +class BroadcastsResourceWithRawResponse: + def __init__(self, broadcasts: BroadcastsResource) -> None: + self._broadcasts = broadcasts + + self.create = to_raw_response_wrapper( + broadcasts.create, + ) + self.retrieve = to_raw_response_wrapper( + broadcasts.retrieve, + ) + self.update = to_raw_response_wrapper( + broadcasts.update, + ) + self.list = to_raw_response_wrapper( + broadcasts.list, + ) + self.archive = to_raw_response_wrapper( + broadcasts.archive, + ) + self.cancel = to_raw_response_wrapper( + broadcasts.cancel, + ) + self.duplicate = to_raw_response_wrapper( + broadcasts.duplicate, + ) + self.put_content = to_raw_response_wrapper( + broadcasts.put_content, + ) + self.retrieve_content = to_raw_response_wrapper( + broadcasts.retrieve_content, + ) + self.schedule = to_raw_response_wrapper( + broadcasts.schedule, + ) + self.send = to_raw_response_wrapper( + broadcasts.send, + ) + + +class AsyncBroadcastsResourceWithRawResponse: + def __init__(self, broadcasts: AsyncBroadcastsResource) -> None: + self._broadcasts = broadcasts + + self.create = async_to_raw_response_wrapper( + broadcasts.create, + ) + self.retrieve = async_to_raw_response_wrapper( + broadcasts.retrieve, + ) + self.update = async_to_raw_response_wrapper( + broadcasts.update, + ) + self.list = async_to_raw_response_wrapper( + broadcasts.list, + ) + self.archive = async_to_raw_response_wrapper( + broadcasts.archive, + ) + self.cancel = async_to_raw_response_wrapper( + broadcasts.cancel, + ) + self.duplicate = async_to_raw_response_wrapper( + broadcasts.duplicate, + ) + self.put_content = async_to_raw_response_wrapper( + broadcasts.put_content, + ) + self.retrieve_content = async_to_raw_response_wrapper( + broadcasts.retrieve_content, + ) + self.schedule = async_to_raw_response_wrapper( + broadcasts.schedule, + ) + self.send = async_to_raw_response_wrapper( + broadcasts.send, + ) + + +class BroadcastsResourceWithStreamingResponse: + def __init__(self, broadcasts: BroadcastsResource) -> None: + self._broadcasts = broadcasts + + self.create = to_streamed_response_wrapper( + broadcasts.create, + ) + self.retrieve = to_streamed_response_wrapper( + broadcasts.retrieve, + ) + self.update = to_streamed_response_wrapper( + broadcasts.update, + ) + self.list = to_streamed_response_wrapper( + broadcasts.list, + ) + self.archive = to_streamed_response_wrapper( + broadcasts.archive, + ) + self.cancel = to_streamed_response_wrapper( + broadcasts.cancel, + ) + self.duplicate = to_streamed_response_wrapper( + broadcasts.duplicate, + ) + self.put_content = to_streamed_response_wrapper( + broadcasts.put_content, + ) + self.retrieve_content = to_streamed_response_wrapper( + broadcasts.retrieve_content, + ) + self.schedule = to_streamed_response_wrapper( + broadcasts.schedule, + ) + self.send = to_streamed_response_wrapper( + broadcasts.send, + ) + + +class AsyncBroadcastsResourceWithStreamingResponse: + def __init__(self, broadcasts: AsyncBroadcastsResource) -> None: + self._broadcasts = broadcasts + + self.create = async_to_streamed_response_wrapper( + broadcasts.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + broadcasts.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + broadcasts.update, + ) + self.list = async_to_streamed_response_wrapper( + broadcasts.list, + ) + self.archive = async_to_streamed_response_wrapper( + broadcasts.archive, + ) + self.cancel = async_to_streamed_response_wrapper( + broadcasts.cancel, + ) + self.duplicate = async_to_streamed_response_wrapper( + broadcasts.duplicate, + ) + self.put_content = async_to_streamed_response_wrapper( + broadcasts.put_content, + ) + self.retrieve_content = async_to_streamed_response_wrapper( + broadcasts.retrieve_content, + ) + self.schedule = async_to_streamed_response_wrapper( + broadcasts.schedule, + ) + self.send = async_to_streamed_response_wrapper( + broadcasts.send, + ) diff --git a/src/courier/resources/digests/__init__.py b/src/courier/resources/digests/__init__.py new file mode 100644 index 00000000..d1ec65bf --- /dev/null +++ b/src/courier/resources/digests/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .digests import ( + DigestsResource, + AsyncDigestsResource, + DigestsResourceWithRawResponse, + AsyncDigestsResourceWithRawResponse, + DigestsResourceWithStreamingResponse, + AsyncDigestsResourceWithStreamingResponse, +) +from .schedules import ( + SchedulesResource, + AsyncSchedulesResource, + SchedulesResourceWithRawResponse, + AsyncSchedulesResourceWithRawResponse, + SchedulesResourceWithStreamingResponse, + AsyncSchedulesResourceWithStreamingResponse, +) + +__all__ = [ + "SchedulesResource", + "AsyncSchedulesResource", + "SchedulesResourceWithRawResponse", + "AsyncSchedulesResourceWithRawResponse", + "SchedulesResourceWithStreamingResponse", + "AsyncSchedulesResourceWithStreamingResponse", + "DigestsResource", + "AsyncDigestsResource", + "DigestsResourceWithRawResponse", + "AsyncDigestsResourceWithRawResponse", + "DigestsResourceWithStreamingResponse", + "AsyncDigestsResourceWithStreamingResponse", +] diff --git a/src/courier/resources/digests/digests.py b/src/courier/resources/digests/digests.py new file mode 100644 index 00000000..d2d31d1e --- /dev/null +++ b/src/courier/resources/digests/digests.py @@ -0,0 +1,120 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ..._compat import cached_property +from .schedules import ( + SchedulesResource, + AsyncSchedulesResource, + SchedulesResourceWithRawResponse, + AsyncSchedulesResourceWithRawResponse, + SchedulesResourceWithStreamingResponse, + AsyncSchedulesResourceWithStreamingResponse, +) +from ..._resource import SyncAPIResource, AsyncAPIResource + +__all__ = ["DigestsResource", "AsyncDigestsResource"] + + +class DigestsResource(SyncAPIResource): + @cached_property + def schedules(self) -> SchedulesResource: + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + return SchedulesResource(self._client) + + @cached_property + def with_raw_response(self) -> DigestsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return DigestsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> DigestsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return DigestsResourceWithStreamingResponse(self) + + +class AsyncDigestsResource(AsyncAPIResource): + @cached_property + def schedules(self) -> AsyncSchedulesResource: + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + return AsyncSchedulesResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncDigestsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncDigestsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncDigestsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncDigestsResourceWithStreamingResponse(self) + + +class DigestsResourceWithRawResponse: + def __init__(self, digests: DigestsResource) -> None: + self._digests = digests + + @cached_property + def schedules(self) -> SchedulesResourceWithRawResponse: + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + return SchedulesResourceWithRawResponse(self._digests.schedules) + + +class AsyncDigestsResourceWithRawResponse: + def __init__(self, digests: AsyncDigestsResource) -> None: + self._digests = digests + + @cached_property + def schedules(self) -> AsyncSchedulesResourceWithRawResponse: + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + return AsyncSchedulesResourceWithRawResponse(self._digests.schedules) + + +class DigestsResourceWithStreamingResponse: + def __init__(self, digests: DigestsResource) -> None: + self._digests = digests + + @cached_property + def schedules(self) -> SchedulesResourceWithStreamingResponse: + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + return SchedulesResourceWithStreamingResponse(self._digests.schedules) + + +class AsyncDigestsResourceWithStreamingResponse: + def __init__(self, digests: AsyncDigestsResource) -> None: + self._digests = digests + + @cached_property + def schedules(self) -> AsyncSchedulesResourceWithStreamingResponse: + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + return AsyncSchedulesResourceWithStreamingResponse(self._digests.schedules) diff --git a/src/courier/resources/digests/schedules.py b/src/courier/resources/digests/schedules.py new file mode 100644 index 00000000..006e4b5d --- /dev/null +++ b/src/courier/resources/digests/schedules.py @@ -0,0 +1,291 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.digests import schedule_list_instances_params +from ...types.digest_instance_list_response import DigestInstanceListResponse + +__all__ = ["SchedulesResource", "AsyncSchedulesResource"] + + +class SchedulesResource(SyncAPIResource): + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + + @cached_property + def with_raw_response(self) -> SchedulesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return SchedulesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> SchedulesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return SchedulesResourceWithStreamingResponse(self) + + def list_instances( + self, + schedule_id: str, + *, + cursor: str | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> DigestInstanceListResponse: + """ + Returns the digest instances for a schedule, one per user, with cursor paging. + Use it to see what has accumulated before a digest releases. + + Args: + cursor: A cursor token from a previous response, used to fetch the next page of results. + + limit: The maximum number of digest instances to return. Defaults to 20, with a maximum + of 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schedule_id: + raise ValueError(f"Expected a non-empty value for `schedule_id` but received {schedule_id!r}") + return self._get( + path_template("/digests/schedules/{schedule_id}/instances", schedule_id=schedule_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + schedule_list_instances_params.ScheduleListInstancesParams, + ), + ), + cast_to=DigestInstanceListResponse, + ) + + def release( + self, + schedule_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Send a digest now instead of waiting for its scheduled time, so your users get + what they have collected so far right away. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schedule_id: + raise ValueError(f"Expected a non-empty value for `schedule_id` but received {schedule_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._post( + path_template("/digests/schedules/{schedule_id}/trigger", schedule_id=schedule_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncSchedulesResource(AsyncAPIResource): + """ + Inspect what has accumulated in a digest schedule and release a digest ahead of its next scheduled delivery. + """ + + @cached_property + def with_raw_response(self) -> AsyncSchedulesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncSchedulesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncSchedulesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncSchedulesResourceWithStreamingResponse(self) + + async def list_instances( + self, + schedule_id: str, + *, + cursor: str | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> DigestInstanceListResponse: + """ + Returns the digest instances for a schedule, one per user, with cursor paging. + Use it to see what has accumulated before a digest releases. + + Args: + cursor: A cursor token from a previous response, used to fetch the next page of results. + + limit: The maximum number of digest instances to return. Defaults to 20, with a maximum + of 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schedule_id: + raise ValueError(f"Expected a non-empty value for `schedule_id` but received {schedule_id!r}") + return await self._get( + path_template("/digests/schedules/{schedule_id}/instances", schedule_id=schedule_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + schedule_list_instances_params.ScheduleListInstancesParams, + ), + ), + cast_to=DigestInstanceListResponse, + ) + + async def release( + self, + schedule_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Send a digest now instead of waiting for its scheduled time, so your users get + what they have collected so far right away. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not schedule_id: + raise ValueError(f"Expected a non-empty value for `schedule_id` but received {schedule_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._post( + path_template("/digests/schedules/{schedule_id}/trigger", schedule_id=schedule_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class SchedulesResourceWithRawResponse: + def __init__(self, schedules: SchedulesResource) -> None: + self._schedules = schedules + + self.list_instances = to_raw_response_wrapper( + schedules.list_instances, + ) + self.release = to_raw_response_wrapper( + schedules.release, + ) + + +class AsyncSchedulesResourceWithRawResponse: + def __init__(self, schedules: AsyncSchedulesResource) -> None: + self._schedules = schedules + + self.list_instances = async_to_raw_response_wrapper( + schedules.list_instances, + ) + self.release = async_to_raw_response_wrapper( + schedules.release, + ) + + +class SchedulesResourceWithStreamingResponse: + def __init__(self, schedules: SchedulesResource) -> None: + self._schedules = schedules + + self.list_instances = to_streamed_response_wrapper( + schedules.list_instances, + ) + self.release = to_streamed_response_wrapper( + schedules.release, + ) + + +class AsyncSchedulesResourceWithStreamingResponse: + def __init__(self, schedules: AsyncSchedulesResource) -> None: + self._schedules = schedules + + self.list_instances = async_to_streamed_response_wrapper( + schedules.list_instances, + ) + self.release = async_to_streamed_response_wrapper( + schedules.release, + ) diff --git a/src/courier/resources/inbound.py b/src/courier/resources/inbound.py new file mode 100644 index 00000000..d5af1bbc --- /dev/null +++ b/src/courier/resources/inbound.py @@ -0,0 +1,220 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal + +import httpx + +from ..types import inbound_track_event_params +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.inbound_track_event_response import InboundTrackEventResponse + +__all__ = ["InboundResource", "AsyncInboundResource"] + + +class InboundResource(SyncAPIResource): + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + + @cached_property + def with_raw_response(self) -> InboundResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return InboundResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> InboundResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return InboundResourceWithStreamingResponse(self) + + def track_event( + self, + *, + event: str, + message_id: str, + properties: Dict[str, object], + type: Literal["track"], + user_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> InboundTrackEventResponse: + """Records an inbound event that can trigger a journey. + + Requires an event name, a + messageId you generate, a type, and a properties object. + + Args: + event: A descriptive name of the event. This name will appear as a trigger in the + Courier Automation Trigger node. + + message_id: A required unique identifier that will be used to de-duplicate requests. If not + unique, will respond with 409 Conflict status + + user_id: The user id associated with the track + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/inbound/courier", + body=maybe_transform( + { + "event": event, + "message_id": message_id, + "properties": properties, + "type": type, + "user_id": user_id, + }, + inbound_track_event_params.InboundTrackEventParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=InboundTrackEventResponse, + ) + + +class AsyncInboundResource(AsyncAPIResource): + """ + Record an inbound event that triggers the journeys and automations mapped to it. + """ + + @cached_property + def with_raw_response(self) -> AsyncInboundResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncInboundResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncInboundResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncInboundResourceWithStreamingResponse(self) + + async def track_event( + self, + *, + event: str, + message_id: str, + properties: Dict[str, object], + type: Literal["track"], + user_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> InboundTrackEventResponse: + """Records an inbound event that can trigger a journey. + + Requires an event name, a + messageId you generate, a type, and a properties object. + + Args: + event: A descriptive name of the event. This name will appear as a trigger in the + Courier Automation Trigger node. + + message_id: A required unique identifier that will be used to de-duplicate requests. If not + unique, will respond with 409 Conflict status + + user_id: The user id associated with the track + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/inbound/courier", + body=await async_maybe_transform( + { + "event": event, + "message_id": message_id, + "properties": properties, + "type": type, + "user_id": user_id, + }, + inbound_track_event_params.InboundTrackEventParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=InboundTrackEventResponse, + ) + + +class InboundResourceWithRawResponse: + def __init__(self, inbound: InboundResource) -> None: + self._inbound = inbound + + self.track_event = to_raw_response_wrapper( + inbound.track_event, + ) + + +class AsyncInboundResourceWithRawResponse: + def __init__(self, inbound: AsyncInboundResource) -> None: + self._inbound = inbound + + self.track_event = async_to_raw_response_wrapper( + inbound.track_event, + ) + + +class InboundResourceWithStreamingResponse: + def __init__(self, inbound: InboundResource) -> None: + self._inbound = inbound + + self.track_event = to_streamed_response_wrapper( + inbound.track_event, + ) + + +class AsyncInboundResourceWithStreamingResponse: + def __init__(self, inbound: AsyncInboundResource) -> None: + self._inbound = inbound + + self.track_event = async_to_streamed_response_wrapper( + inbound.track_event, + ) diff --git a/src/courier/resources/journeys/__init__.py b/src/courier/resources/journeys/__init__.py new file mode 100644 index 00000000..f705015d --- /dev/null +++ b/src/courier/resources/journeys/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .journeys import ( + JourneysResource, + AsyncJourneysResource, + JourneysResourceWithRawResponse, + AsyncJourneysResourceWithRawResponse, + JourneysResourceWithStreamingResponse, + AsyncJourneysResourceWithStreamingResponse, +) +from .templates import ( + TemplatesResource, + AsyncTemplatesResource, + TemplatesResourceWithRawResponse, + AsyncTemplatesResourceWithRawResponse, + TemplatesResourceWithStreamingResponse, + AsyncTemplatesResourceWithStreamingResponse, +) + +__all__ = [ + "TemplatesResource", + "AsyncTemplatesResource", + "TemplatesResourceWithRawResponse", + "AsyncTemplatesResourceWithRawResponse", + "TemplatesResourceWithStreamingResponse", + "AsyncTemplatesResourceWithStreamingResponse", + "JourneysResource", + "AsyncJourneysResource", + "JourneysResourceWithRawResponse", + "AsyncJourneysResourceWithRawResponse", + "JourneysResourceWithStreamingResponse", + "AsyncJourneysResourceWithStreamingResponse", +] diff --git a/src/courier/resources/journeys/journeys.py b/src/courier/resources/journeys/journeys.py new file mode 100644 index 00000000..7bb1439a --- /dev/null +++ b/src/courier/resources/journeys/journeys.py @@ -0,0 +1,1247 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Any, Dict, Iterable, cast +from typing_extensions import Literal, overload + +import httpx + +from ...types import ( + JourneyState, + journey_list_params, + journey_cancel_params, + journey_create_params, + journey_invoke_params, + journey_publish_params, + journey_replace_params, + journey_retrieve_params, +) +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, required_args, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from .templates import ( + TemplatesResource, + AsyncTemplatesResource, + TemplatesResourceWithRawResponse, + AsyncTemplatesResourceWithRawResponse, + TemplatesResourceWithStreamingResponse, + AsyncTemplatesResourceWithStreamingResponse, +) +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.journey_state import JourneyState +from ...types.journey_response import JourneyResponse +from ...types.journey_node_param import JourneyNodeParam +from ...types.journeys_list_response import JourneysListResponse +from ...types.cancel_journey_response import CancelJourneyResponse +from ...types.journeys_invoke_response import JourneysInvokeResponse +from ...types.journey_versions_list_response import JourneyVersionsListResponse + +__all__ = ["JourneysResource", "AsyncJourneysResource"] + + +class JourneysResource(SyncAPIResource): + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + + @cached_property + def templates(self) -> TemplatesResource: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + return TemplatesResource(self._client) + + @cached_property + def with_raw_response(self) -> JourneysResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return JourneysResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> JourneysResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return JourneysResourceWithStreamingResponse(self) + + def create( + self, + *, + name: str, + nodes: Iterable[JourneyNodeParam], + enabled: bool | Omit = omit, + state: JourneyState | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """ + Creates a journey from a set of nodes, in draft state unless you pass a + published state. Send nodes cannot be included until their templates exist. + + Args: + state: Lifecycle state of a journey. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/journeys", + body=maybe_transform( + { + "name": name, + "nodes": nodes, + "enabled": enabled, + "state": state, + }, + journey_create_params.JourneyCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyResponse, + ) + + def retrieve( + self, + template_id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """Fetch a journey by id. + + Pass `?version=draft` (default `published`) to retrieve + the working draft, or `?version=vN` to retrieve a historical version. + + Args: + version: Version selector: `draft`, `published` (default), or `vN`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._get( + path_template("/journeys/{template_id}", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"version": version}, journey_retrieve_params.JourneyRetrieveParams), + ), + cast_to=JourneyResponse, + ) + + def list( + self, + *, + cursor: str | Omit = omit, + version: Literal["published", "draft"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneysListResponse: + """ + Lists the workspace's journeys, each carrying a name, state, and enabled flag. + Paged by cursor. + + Args: + cursor: A cursor token for pagination. Use the cursor from the previous response to + fetch the next page of results. + + version: The version of journeys to retrieve. Accepted values are published (for + published journeys) or draft (for draft journeys). Defaults to published. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/journeys", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "version": version, + }, + journey_list_params.JourneyListParams, + ), + ), + cast_to=JourneysListResponse, + ) + + def archive( + self, + template_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives a journey so it can no longer be invoked. + + Runs already in flight + continue to completion, so archiving never strands a user mid-sequence. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/journeys/{template_id}", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + @overload + def cancel( + self, + *, + cancelation_token: str, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CancelJourneyResponse: + """ + Cancels in-flight journey runs, either every run sharing a cancelation token or + one run by id. Use it to stop a sequence when the event resolves. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def cancel( + self, + *, + run_id: str, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CancelJourneyResponse: + """ + Cancels in-flight journey runs, either every run sharing a cancelation token or + one run by id. Use it to stop a sequence when the event resolves. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["cancelation_token"], ["run_id"]) + def cancel( + self, + *, + cancelation_token: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + run_id: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CancelJourneyResponse: + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return cast( + CancelJourneyResponse, + self._post( + "/journeys/cancel", + body=maybe_transform( + { + "cancelation_token": cancelation_token, + "run_id": run_id, + }, + journey_cancel_params.JourneyCancelParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=cast( + Any, CancelJourneyResponse + ), # Union types cannot be passed in as arguments in the type system + ), + ) + + def invoke( + self, + template_id: str, + *, + data: Dict[str, object] | Omit = omit, + profile: Dict[str, object] | Omit = omit, + user_id: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneysInvokeResponse: + """Starts a journey run for one user and returns a runId. + + Runs execute + asynchronously, so the response arrives before any message is sent. + + Args: + data: Data payload passed to the journey. The expected shape can be predefined using + the schema builder in the journey editor. This data is available in journey + steps for condition evaluation and template variable interpolation. Can also + contain user identifiers (user_id, userId, anonymousId) if not provided + elsewhere. + + profile: Profile data for the user. Can contain contact information (email, + phone_number), user identifiers (user_id, userId, anonymousId), or any custom + profile fields. Profile fields are merged with any existing stored profile for + the user. Include context.tenant_id to load a tenant-scoped profile for + multi-tenant scenarios. + + user_id: A unique identifier for the user. If not provided, the system will attempt to + resolve the user identifier from profile or data objects. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/journeys/{template_id}/invoke", template_id=template_id), + body=maybe_transform( + { + "data": data, + "profile": profile, + "user_id": user_id, + }, + journey_invoke_params.JourneyInvokeParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneysInvokeResponse, + ) + + def list_versions( + self, + template_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyVersionsListResponse: + """ + Lists a journey's published versions, most recent first, so you have a version + id to roll back to. Paged by cursor. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._get( + path_template("/journeys/{template_id}/versions", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyVersionsListResponse, + ) + + def publish( + self, + template_id: str, + *, + version: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """ + Publishes a journey's current draft as a new version, making it live for new + runs. Pass a version instead to roll back to an earlier one. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/journeys/{template_id}/publish", template_id=template_id), + body=maybe_transform({"version": version}, journey_publish_params.JourneyPublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyResponse, + ) + + def replace( + self, + template_id: str, + *, + name: str, + nodes: Iterable[JourneyNodeParam], + enabled: bool | Omit = omit, + state: JourneyState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """ + Replaces a journey's working draft, leaving the published version live until you + publish. Reach for this when editing a journey already running. + + Args: + state: Lifecycle state of a journey. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._put( + path_template("/journeys/{template_id}", template_id=template_id), + body=maybe_transform( + { + "name": name, + "nodes": nodes, + "enabled": enabled, + "state": state, + }, + journey_replace_params.JourneyReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyResponse, + ) + + +class AsyncJourneysResource(AsyncAPIResource): + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + + @cached_property + def templates(self) -> AsyncTemplatesResource: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + return AsyncTemplatesResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncJourneysResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncJourneysResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncJourneysResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncJourneysResourceWithStreamingResponse(self) + + async def create( + self, + *, + name: str, + nodes: Iterable[JourneyNodeParam], + enabled: bool | Omit = omit, + state: JourneyState | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """ + Creates a journey from a set of nodes, in draft state unless you pass a + published state. Send nodes cannot be included until their templates exist. + + Args: + state: Lifecycle state of a journey. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/journeys", + body=await async_maybe_transform( + { + "name": name, + "nodes": nodes, + "enabled": enabled, + "state": state, + }, + journey_create_params.JourneyCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyResponse, + ) + + async def retrieve( + self, + template_id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """Fetch a journey by id. + + Pass `?version=draft` (default `published`) to retrieve + the working draft, or `?version=vN` to retrieve a historical version. + + Args: + version: Version selector: `draft`, `published` (default), or `vN`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._get( + path_template("/journeys/{template_id}", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"version": version}, journey_retrieve_params.JourneyRetrieveParams), + ), + cast_to=JourneyResponse, + ) + + async def list( + self, + *, + cursor: str | Omit = omit, + version: Literal["published", "draft"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneysListResponse: + """ + Lists the workspace's journeys, each carrying a name, state, and enabled flag. + Paged by cursor. + + Args: + cursor: A cursor token for pagination. Use the cursor from the previous response to + fetch the next page of results. + + version: The version of journeys to retrieve. Accepted values are published (for + published journeys) or draft (for draft journeys). Defaults to published. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/journeys", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "version": version, + }, + journey_list_params.JourneyListParams, + ), + ), + cast_to=JourneysListResponse, + ) + + async def archive( + self, + template_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives a journey so it can no longer be invoked. + + Runs already in flight + continue to completion, so archiving never strands a user mid-sequence. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/journeys/{template_id}", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + @overload + async def cancel( + self, + *, + cancelation_token: str, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CancelJourneyResponse: + """ + Cancels in-flight journey runs, either every run sharing a cancelation token or + one run by id. Use it to stop a sequence when the event resolves. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def cancel( + self, + *, + run_id: str, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CancelJourneyResponse: + """ + Cancels in-flight journey runs, either every run sharing a cancelation token or + one run by id. Use it to stop a sequence when the event resolves. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["cancelation_token"], ["run_id"]) + async def cancel( + self, + *, + cancelation_token: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + run_id: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CancelJourneyResponse: + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return cast( + CancelJourneyResponse, + await self._post( + "/journeys/cancel", + body=await async_maybe_transform( + { + "cancelation_token": cancelation_token, + "run_id": run_id, + }, + journey_cancel_params.JourneyCancelParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=cast( + Any, CancelJourneyResponse + ), # Union types cannot be passed in as arguments in the type system + ), + ) + + async def invoke( + self, + template_id: str, + *, + data: Dict[str, object] | Omit = omit, + profile: Dict[str, object] | Omit = omit, + user_id: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneysInvokeResponse: + """Starts a journey run for one user and returns a runId. + + Runs execute + asynchronously, so the response arrives before any message is sent. + + Args: + data: Data payload passed to the journey. The expected shape can be predefined using + the schema builder in the journey editor. This data is available in journey + steps for condition evaluation and template variable interpolation. Can also + contain user identifiers (user_id, userId, anonymousId) if not provided + elsewhere. + + profile: Profile data for the user. Can contain contact information (email, + phone_number), user identifiers (user_id, userId, anonymousId), or any custom + profile fields. Profile fields are merged with any existing stored profile for + the user. Include context.tenant_id to load a tenant-scoped profile for + multi-tenant scenarios. + + user_id: A unique identifier for the user. If not provided, the system will attempt to + resolve the user identifier from profile or data objects. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/journeys/{template_id}/invoke", template_id=template_id), + body=await async_maybe_transform( + { + "data": data, + "profile": profile, + "user_id": user_id, + }, + journey_invoke_params.JourneyInvokeParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneysInvokeResponse, + ) + + async def list_versions( + self, + template_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyVersionsListResponse: + """ + Lists a journey's published versions, most recent first, so you have a version + id to roll back to. Paged by cursor. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._get( + path_template("/journeys/{template_id}/versions", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyVersionsListResponse, + ) + + async def publish( + self, + template_id: str, + *, + version: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """ + Publishes a journey's current draft as a new version, making it live for new + runs. Pass a version instead to roll back to an earlier one. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/journeys/{template_id}/publish", template_id=template_id), + body=await async_maybe_transform({"version": version}, journey_publish_params.JourneyPublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyResponse, + ) + + async def replace( + self, + template_id: str, + *, + name: str, + nodes: Iterable[JourneyNodeParam], + enabled: bool | Omit = omit, + state: JourneyState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyResponse: + """ + Replaces a journey's working draft, leaving the published version live until you + publish. Reach for this when editing a journey already running. + + Args: + state: Lifecycle state of a journey. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._put( + path_template("/journeys/{template_id}", template_id=template_id), + body=await async_maybe_transform( + { + "name": name, + "nodes": nodes, + "enabled": enabled, + "state": state, + }, + journey_replace_params.JourneyReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyResponse, + ) + + +class JourneysResourceWithRawResponse: + def __init__(self, journeys: JourneysResource) -> None: + self._journeys = journeys + + self.create = to_raw_response_wrapper( + journeys.create, + ) + self.retrieve = to_raw_response_wrapper( + journeys.retrieve, + ) + self.list = to_raw_response_wrapper( + journeys.list, + ) + self.archive = to_raw_response_wrapper( + journeys.archive, + ) + self.cancel = to_raw_response_wrapper( + journeys.cancel, + ) + self.invoke = to_raw_response_wrapper( + journeys.invoke, + ) + self.list_versions = to_raw_response_wrapper( + journeys.list_versions, + ) + self.publish = to_raw_response_wrapper( + journeys.publish, + ) + self.replace = to_raw_response_wrapper( + journeys.replace, + ) + + @cached_property + def templates(self) -> TemplatesResourceWithRawResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + return TemplatesResourceWithRawResponse(self._journeys.templates) + + +class AsyncJourneysResourceWithRawResponse: + def __init__(self, journeys: AsyncJourneysResource) -> None: + self._journeys = journeys + + self.create = async_to_raw_response_wrapper( + journeys.create, + ) + self.retrieve = async_to_raw_response_wrapper( + journeys.retrieve, + ) + self.list = async_to_raw_response_wrapper( + journeys.list, + ) + self.archive = async_to_raw_response_wrapper( + journeys.archive, + ) + self.cancel = async_to_raw_response_wrapper( + journeys.cancel, + ) + self.invoke = async_to_raw_response_wrapper( + journeys.invoke, + ) + self.list_versions = async_to_raw_response_wrapper( + journeys.list_versions, + ) + self.publish = async_to_raw_response_wrapper( + journeys.publish, + ) + self.replace = async_to_raw_response_wrapper( + journeys.replace, + ) + + @cached_property + def templates(self) -> AsyncTemplatesResourceWithRawResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + return AsyncTemplatesResourceWithRawResponse(self._journeys.templates) + + +class JourneysResourceWithStreamingResponse: + def __init__(self, journeys: JourneysResource) -> None: + self._journeys = journeys + + self.create = to_streamed_response_wrapper( + journeys.create, + ) + self.retrieve = to_streamed_response_wrapper( + journeys.retrieve, + ) + self.list = to_streamed_response_wrapper( + journeys.list, + ) + self.archive = to_streamed_response_wrapper( + journeys.archive, + ) + self.cancel = to_streamed_response_wrapper( + journeys.cancel, + ) + self.invoke = to_streamed_response_wrapper( + journeys.invoke, + ) + self.list_versions = to_streamed_response_wrapper( + journeys.list_versions, + ) + self.publish = to_streamed_response_wrapper( + journeys.publish, + ) + self.replace = to_streamed_response_wrapper( + journeys.replace, + ) + + @cached_property + def templates(self) -> TemplatesResourceWithStreamingResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + return TemplatesResourceWithStreamingResponse(self._journeys.templates) + + +class AsyncJourneysResourceWithStreamingResponse: + def __init__(self, journeys: AsyncJourneysResource) -> None: + self._journeys = journeys + + self.create = async_to_streamed_response_wrapper( + journeys.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + journeys.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + journeys.list, + ) + self.archive = async_to_streamed_response_wrapper( + journeys.archive, + ) + self.cancel = async_to_streamed_response_wrapper( + journeys.cancel, + ) + self.invoke = async_to_streamed_response_wrapper( + journeys.invoke, + ) + self.list_versions = async_to_streamed_response_wrapper( + journeys.list_versions, + ) + self.publish = async_to_streamed_response_wrapper( + journeys.publish, + ) + self.replace = async_to_streamed_response_wrapper( + journeys.replace, + ) + + @cached_property + def templates(self) -> AsyncTemplatesResourceWithStreamingResponse: + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + return AsyncTemplatesResourceWithStreamingResponse(self._journeys.templates) diff --git a/src/courier/resources/journeys/templates.py b/src/courier/resources/journeys/templates.py new file mode 100644 index 00000000..b030ff6c --- /dev/null +++ b/src/courier/resources/journeys/templates.py @@ -0,0 +1,1243 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable + +import httpx + +from ...types import NotificationTemplateState +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.journeys import ( + template_list_params, + template_create_params, + template_publish_params, + template_replace_params, + template_put_locale_params, + template_put_content_params, + template_retrieve_content_params, +) +from ...types.notification_template_state import NotificationTemplateState +from ...types.journey_template_get_response import JourneyTemplateGetResponse +from ...types.journey_template_list_response import JourneyTemplateListResponse +from ...types.notification_content_get_response import NotificationContentGetResponse +from ...types.notification_content_mutation_response import NotificationContentMutationResponse +from ...types.notification_template_version_list_response import NotificationTemplateVersionListResponse + +__all__ = ["TemplatesResource", "AsyncTemplatesResource"] + + +class TemplatesResource(SyncAPIResource): + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + + @cached_property + def with_raw_response(self) -> TemplatesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TemplatesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TemplatesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TemplatesResourceWithStreamingResponse(self) + + def create( + self, + template_id: str, + *, + channel: str, + notification: template_create_params.Notification, + provider_key: str | Omit = omit, + state: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateGetResponse: + """Create a notification template scoped to this journey. + + Defaults to `DRAFT` + state; pass `state: "PUBLISHED"` to publish on create. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/journeys/{template_id}/templates", template_id=template_id), + body=maybe_transform( + { + "channel": channel, + "notification": notification, + "provider_key": provider_key, + "state": state, + }, + template_create_params.TemplateCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyTemplateGetResponse, + ) + + def retrieve( + self, + notification_id: str, + *, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateGetResponse: + """ + Returns a journey's own notification template with its name, brand, subscription + topic, and content. Defaults to the published version. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return self._get( + path_template( + "/journeys/{template_id}/templates/{notification_id}", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyTemplateGetResponse, + ) + + def list( + self, + template_id: str, + *, + cursor: str | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateListResponse: + """List notification templates scoped to this journey. + + Journey-scoped notification + templates can only be referenced from `send` nodes within the same journey. + + Args: + cursor: Pagination cursor from a prior response. + + limit: Page size. Minimum 1, maximum 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._get( + path_template("/journeys/{template_id}/templates", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + template_list_params.TemplateListParams, + ), + ), + cast_to=JourneyTemplateListResponse, + ) + + def archive( + self, + notification_id: str, + *, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives one journey's notification template, preventing further sends. + + Detach + any send node referencing it beforehand. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template( + "/journeys/{template_id}/templates/{notification_id}", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def list_versions( + self, + notification_id: str, + *, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateVersionListResponse: + """ + Lists the published versions of a template that belongs to a journey, most + recent first. Paged by cursor. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return self._get( + path_template( + "/journeys/{template_id}/templates/{notification_id}/versions", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateVersionListResponse, + ) + + def publish( + self, + notification_id: str, + *, + template_id: str, + version: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Publishes a journey-scoped template's draft as a new version. + + Pass a version + instead to roll back the template to an earlier publish. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template( + "/journeys/{template_id}/templates/{notification_id}/publish", + template_id=template_id, + notification_id=notification_id, + ), + body=maybe_transform({"version": version}, template_publish_params.TemplatePublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def put_content( + self, + notification_id: str, + *, + template_id: str, + content: template_put_content_params.Content, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """ + Replace the elemental content of a journey-scoped notification template. + Overwrites all elements in the template draft with the provided content. + + Args: + content: Elemental content payload. The server defaults `version` when omitted. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return self._put( + path_template( + "/journeys/{template_id}/templates/{notification_id}/content", + template_id=template_id, + notification_id=notification_id, + ), + body=maybe_transform( + { + "content": content, + "state": state, + }, + template_put_content_params.TemplatePutContentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + def put_locale( + self, + locale_id: str, + *, + template_id: str, + notification_id: str, + elements: Iterable[template_put_locale_params.Element], + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """Set locale-specific content overrides for a journey-scoped notification + template. + + Each element override must reference an existing element by ID. + + Args: + elements: Elements with locale-specific content overrides. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + if not locale_id: + raise ValueError(f"Expected a non-empty value for `locale_id` but received {locale_id!r}") + return self._put( + path_template( + "/journeys/{template_id}/templates/{notification_id}/locales/{locale_id}", + template_id=template_id, + notification_id=notification_id, + locale_id=locale_id, + ), + body=maybe_transform( + { + "elements": elements, + "state": state, + }, + template_put_locale_params.TemplatePutLocaleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + def replace( + self, + notification_id: str, + *, + template_id: str, + notification: template_replace_params.Notification, + state: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateGetResponse: + """Replaces the draft content of one journey's notification template. + + Publish it + before send nodes referencing it render the change. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return self._put( + path_template( + "/journeys/{template_id}/templates/{notification_id}", + template_id=template_id, + notification_id=notification_id, + ), + body=maybe_transform( + { + "notification": notification, + "state": state, + }, + template_replace_params.TemplateReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyTemplateGetResponse, + ) + + def retrieve_content( + self, + notification_id: str, + *, + template_id: str, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentGetResponse: + """ + Returns the Elemental elements and version of a journey-scoped template's + content. Compare versions to see what changed between publishes. + + Args: + version: Accepts `draft`, `published`, or a version string (e.g., `v001`). Defaults to + `published`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return self._get( + path_template( + "/journeys/{template_id}/templates/{notification_id}/content", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"version": version}, template_retrieve_content_params.TemplateRetrieveContentParams + ), + ), + cast_to=NotificationContentGetResponse, + ) + + +class AsyncTemplatesResource(AsyncAPIResource): + """ + Build, version, publish, invoke, and cancel multi-step notification workflows, along with the templates scoped to them. + """ + + @cached_property + def with_raw_response(self) -> AsyncTemplatesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTemplatesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTemplatesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTemplatesResourceWithStreamingResponse(self) + + async def create( + self, + template_id: str, + *, + channel: str, + notification: template_create_params.Notification, + provider_key: str | Omit = omit, + state: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateGetResponse: + """Create a notification template scoped to this journey. + + Defaults to `DRAFT` + state; pass `state: "PUBLISHED"` to publish on create. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/journeys/{template_id}/templates", template_id=template_id), + body=await async_maybe_transform( + { + "channel": channel, + "notification": notification, + "provider_key": provider_key, + "state": state, + }, + template_create_params.TemplateCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyTemplateGetResponse, + ) + + async def retrieve( + self, + notification_id: str, + *, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateGetResponse: + """ + Returns a journey's own notification template with its name, brand, subscription + topic, and content. Defaults to the published version. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return await self._get( + path_template( + "/journeys/{template_id}/templates/{notification_id}", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyTemplateGetResponse, + ) + + async def list( + self, + template_id: str, + *, + cursor: str | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateListResponse: + """List notification templates scoped to this journey. + + Journey-scoped notification + templates can only be referenced from `send` nodes within the same journey. + + Args: + cursor: Pagination cursor from a prior response. + + limit: Page size. Minimum 1, maximum 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._get( + path_template("/journeys/{template_id}/templates", template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + template_list_params.TemplateListParams, + ), + ), + cast_to=JourneyTemplateListResponse, + ) + + async def archive( + self, + notification_id: str, + *, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives one journey's notification template, preventing further sends. + + Detach + any send node referencing it beforehand. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template( + "/journeys/{template_id}/templates/{notification_id}", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def list_versions( + self, + notification_id: str, + *, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateVersionListResponse: + """ + Lists the published versions of a template that belongs to a journey, most + recent first. Paged by cursor. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return await self._get( + path_template( + "/journeys/{template_id}/templates/{notification_id}/versions", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateVersionListResponse, + ) + + async def publish( + self, + notification_id: str, + *, + template_id: str, + version: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Publishes a journey-scoped template's draft as a new version. + + Pass a version + instead to roll back the template to an earlier publish. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template( + "/journeys/{template_id}/templates/{notification_id}/publish", + template_id=template_id, + notification_id=notification_id, + ), + body=await async_maybe_transform({"version": version}, template_publish_params.TemplatePublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def put_content( + self, + notification_id: str, + *, + template_id: str, + content: template_put_content_params.Content, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """ + Replace the elemental content of a journey-scoped notification template. + Overwrites all elements in the template draft with the provided content. + + Args: + content: Elemental content payload. The server defaults `version` when omitted. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return await self._put( + path_template( + "/journeys/{template_id}/templates/{notification_id}/content", + template_id=template_id, + notification_id=notification_id, + ), + body=await async_maybe_transform( + { + "content": content, + "state": state, + }, + template_put_content_params.TemplatePutContentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + async def put_locale( + self, + locale_id: str, + *, + template_id: str, + notification_id: str, + elements: Iterable[template_put_locale_params.Element], + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """Set locale-specific content overrides for a journey-scoped notification + template. + + Each element override must reference an existing element by ID. + + Args: + elements: Elements with locale-specific content overrides. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + if not locale_id: + raise ValueError(f"Expected a non-empty value for `locale_id` but received {locale_id!r}") + return await self._put( + path_template( + "/journeys/{template_id}/templates/{notification_id}/locales/{locale_id}", + template_id=template_id, + notification_id=notification_id, + locale_id=locale_id, + ), + body=await async_maybe_transform( + { + "elements": elements, + "state": state, + }, + template_put_locale_params.TemplatePutLocaleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + async def replace( + self, + notification_id: str, + *, + template_id: str, + notification: template_replace_params.Notification, + state: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> JourneyTemplateGetResponse: + """Replaces the draft content of one journey's notification template. + + Publish it + before send nodes referencing it render the change. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return await self._put( + path_template( + "/journeys/{template_id}/templates/{notification_id}", + template_id=template_id, + notification_id=notification_id, + ), + body=await async_maybe_transform( + { + "notification": notification, + "state": state, + }, + template_replace_params.TemplateReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=JourneyTemplateGetResponse, + ) + + async def retrieve_content( + self, + notification_id: str, + *, + template_id: str, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentGetResponse: + """ + Returns the Elemental elements and version of a journey-scoped template's + content. Compare versions to see what changed between publishes. + + Args: + version: Accepts `draft`, `published`, or a version string (e.g., `v001`). Defaults to + `published`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not notification_id: + raise ValueError(f"Expected a non-empty value for `notification_id` but received {notification_id!r}") + return await self._get( + path_template( + "/journeys/{template_id}/templates/{notification_id}/content", + template_id=template_id, + notification_id=notification_id, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"version": version}, template_retrieve_content_params.TemplateRetrieveContentParams + ), + ), + cast_to=NotificationContentGetResponse, + ) + + +class TemplatesResourceWithRawResponse: + def __init__(self, templates: TemplatesResource) -> None: + self._templates = templates + + self.create = to_raw_response_wrapper( + templates.create, + ) + self.retrieve = to_raw_response_wrapper( + templates.retrieve, + ) + self.list = to_raw_response_wrapper( + templates.list, + ) + self.archive = to_raw_response_wrapper( + templates.archive, + ) + self.list_versions = to_raw_response_wrapper( + templates.list_versions, + ) + self.publish = to_raw_response_wrapper( + templates.publish, + ) + self.put_content = to_raw_response_wrapper( + templates.put_content, + ) + self.put_locale = to_raw_response_wrapper( + templates.put_locale, + ) + self.replace = to_raw_response_wrapper( + templates.replace, + ) + self.retrieve_content = to_raw_response_wrapper( + templates.retrieve_content, + ) + + +class AsyncTemplatesResourceWithRawResponse: + def __init__(self, templates: AsyncTemplatesResource) -> None: + self._templates = templates + + self.create = async_to_raw_response_wrapper( + templates.create, + ) + self.retrieve = async_to_raw_response_wrapper( + templates.retrieve, + ) + self.list = async_to_raw_response_wrapper( + templates.list, + ) + self.archive = async_to_raw_response_wrapper( + templates.archive, + ) + self.list_versions = async_to_raw_response_wrapper( + templates.list_versions, + ) + self.publish = async_to_raw_response_wrapper( + templates.publish, + ) + self.put_content = async_to_raw_response_wrapper( + templates.put_content, + ) + self.put_locale = async_to_raw_response_wrapper( + templates.put_locale, + ) + self.replace = async_to_raw_response_wrapper( + templates.replace, + ) + self.retrieve_content = async_to_raw_response_wrapper( + templates.retrieve_content, + ) + + +class TemplatesResourceWithStreamingResponse: + def __init__(self, templates: TemplatesResource) -> None: + self._templates = templates + + self.create = to_streamed_response_wrapper( + templates.create, + ) + self.retrieve = to_streamed_response_wrapper( + templates.retrieve, + ) + self.list = to_streamed_response_wrapper( + templates.list, + ) + self.archive = to_streamed_response_wrapper( + templates.archive, + ) + self.list_versions = to_streamed_response_wrapper( + templates.list_versions, + ) + self.publish = to_streamed_response_wrapper( + templates.publish, + ) + self.put_content = to_streamed_response_wrapper( + templates.put_content, + ) + self.put_locale = to_streamed_response_wrapper( + templates.put_locale, + ) + self.replace = to_streamed_response_wrapper( + templates.replace, + ) + self.retrieve_content = to_streamed_response_wrapper( + templates.retrieve_content, + ) + + +class AsyncTemplatesResourceWithStreamingResponse: + def __init__(self, templates: AsyncTemplatesResource) -> None: + self._templates = templates + + self.create = async_to_streamed_response_wrapper( + templates.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + templates.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + templates.list, + ) + self.archive = async_to_streamed_response_wrapper( + templates.archive, + ) + self.list_versions = async_to_streamed_response_wrapper( + templates.list_versions, + ) + self.publish = async_to_streamed_response_wrapper( + templates.publish, + ) + self.put_content = async_to_streamed_response_wrapper( + templates.put_content, + ) + self.put_locale = async_to_streamed_response_wrapper( + templates.put_locale, + ) + self.replace = async_to_streamed_response_wrapper( + templates.replace, + ) + self.retrieve_content = async_to_streamed_response_wrapper( + templates.retrieve_content, + ) diff --git a/src/courier/resources/lists/__init__.py b/src/courier/resources/lists/__init__.py new file mode 100644 index 00000000..06c9d679 --- /dev/null +++ b/src/courier/resources/lists/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .lists import ( + ListsResource, + AsyncListsResource, + ListsResourceWithRawResponse, + AsyncListsResourceWithRawResponse, + ListsResourceWithStreamingResponse, + AsyncListsResourceWithStreamingResponse, +) +from .subscriptions import ( + SubscriptionsResource, + AsyncSubscriptionsResource, + SubscriptionsResourceWithRawResponse, + AsyncSubscriptionsResourceWithRawResponse, + SubscriptionsResourceWithStreamingResponse, + AsyncSubscriptionsResourceWithStreamingResponse, +) + +__all__ = [ + "SubscriptionsResource", + "AsyncSubscriptionsResource", + "SubscriptionsResourceWithRawResponse", + "AsyncSubscriptionsResourceWithRawResponse", + "SubscriptionsResourceWithStreamingResponse", + "AsyncSubscriptionsResourceWithStreamingResponse", + "ListsResource", + "AsyncListsResource", + "ListsResourceWithRawResponse", + "AsyncListsResourceWithRawResponse", + "ListsResourceWithStreamingResponse", + "AsyncListsResourceWithStreamingResponse", +] diff --git a/src/courier/resources/lists/lists.py b/src/courier/resources/lists/lists.py new file mode 100644 index 00000000..95b43ebd --- /dev/null +++ b/src/courier/resources/lists/lists.py @@ -0,0 +1,613 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +import httpx + +from ...types import list_list_params, list_update_params +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .subscriptions import ( + SubscriptionsResource, + AsyncSubscriptionsResource, + SubscriptionsResourceWithRawResponse, + AsyncSubscriptionsResourceWithRawResponse, + SubscriptionsResourceWithStreamingResponse, + AsyncSubscriptionsResourceWithStreamingResponse, +) +from ..._base_client import make_request_options +from ...types.subscription_list import SubscriptionList +from ...types.list_list_response import ListListResponse +from ...types.shared_params.recipient_preferences import RecipientPreferences + +__all__ = ["ListsResource", "AsyncListsResource"] + + +class ListsResource(SyncAPIResource): + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + + @cached_property + def subscriptions(self) -> SubscriptionsResource: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + return SubscriptionsResource(self._client) + + @cached_property + def with_raw_response(self) -> ListsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return ListsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ListsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return ListsResourceWithStreamingResponse(self) + + def retrieve( + self, + list_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> SubscriptionList: + """Returns one list by id with its name and created and updated timestamps. + + Fetch + its subscribers separately with the subscriptions endpoint. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + return self._get( + path_template("/lists/{list_id}", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=SubscriptionList, + ) + + def update( + self, + list_id: str, + *, + name: str, + preferences: Optional[RecipientPreferences] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Creates or replaces a list from a name and preferences. + + Subscribers are managed + through the separate subscriptions endpoints. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/lists/{list_id}", list_id=list_id), + body=maybe_transform( + { + "name": name, + "preferences": preferences, + }, + list_update_params.ListUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + pattern: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListListResponse: + """ + Returns the workspace's lists, filterable by a pattern to fetch a subset such as + every regional list. Paged by cursor. + + Args: + cursor: A unique identifier that allows for fetching the next page of lists. + + pattern: + "A pattern used to filter the list items returned. Pattern types supported: + exact match on `list_id` or a pattern of one or more pattern parts. you may + replace a part with either: `*` to match all parts in that position, or `**` to + signify a wildcard `endsWith` pattern match." + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/lists", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "pattern": pattern, + }, + list_list_params.ListListParams, + ), + ), + cast_to=ListListResponse, + ) + + def delete( + self, + list_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a list, halting sends that target it. + + A previously deleted list can be + brought back with the companion restore endpoint. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/lists/{list_id}", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def restore( + self, + list_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Restores a previously deleted list along with its subscribers, so a list removed + by mistake can be brought back rather than rebuilt. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/lists/{list_id}/restore", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncListsResource(AsyncAPIResource): + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + + @cached_property + def subscriptions(self) -> AsyncSubscriptionsResource: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + return AsyncSubscriptionsResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncListsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncListsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncListsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncListsResourceWithStreamingResponse(self) + + async def retrieve( + self, + list_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> SubscriptionList: + """Returns one list by id with its name and created and updated timestamps. + + Fetch + its subscribers separately with the subscriptions endpoint. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + return await self._get( + path_template("/lists/{list_id}", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=SubscriptionList, + ) + + async def update( + self, + list_id: str, + *, + name: str, + preferences: Optional[RecipientPreferences] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Creates or replaces a list from a name and preferences. + + Subscribers are managed + through the separate subscriptions endpoints. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/lists/{list_id}", list_id=list_id), + body=await async_maybe_transform( + { + "name": name, + "preferences": preferences, + }, + list_update_params.ListUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + pattern: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListListResponse: + """ + Returns the workspace's lists, filterable by a pattern to fetch a subset such as + every regional list. Paged by cursor. + + Args: + cursor: A unique identifier that allows for fetching the next page of lists. + + pattern: + "A pattern used to filter the list items returned. Pattern types supported: + exact match on `list_id` or a pattern of one or more pattern parts. you may + replace a part with either: `*` to match all parts in that position, or `**` to + signify a wildcard `endsWith` pattern match." + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/lists", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "pattern": pattern, + }, + list_list_params.ListListParams, + ), + ), + cast_to=ListListResponse, + ) + + async def delete( + self, + list_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a list, halting sends that target it. + + A previously deleted list can be + brought back with the companion restore endpoint. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/lists/{list_id}", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def restore( + self, + list_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Restores a previously deleted list along with its subscribers, so a list removed + by mistake can be brought back rather than rebuilt. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/lists/{list_id}/restore", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class ListsResourceWithRawResponse: + def __init__(self, lists: ListsResource) -> None: + self._lists = lists + + self.retrieve = to_raw_response_wrapper( + lists.retrieve, + ) + self.update = to_raw_response_wrapper( + lists.update, + ) + self.list = to_raw_response_wrapper( + lists.list, + ) + self.delete = to_raw_response_wrapper( + lists.delete, + ) + self.restore = to_raw_response_wrapper( + lists.restore, + ) + + @cached_property + def subscriptions(self) -> SubscriptionsResourceWithRawResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + return SubscriptionsResourceWithRawResponse(self._lists.subscriptions) + + +class AsyncListsResourceWithRawResponse: + def __init__(self, lists: AsyncListsResource) -> None: + self._lists = lists + + self.retrieve = async_to_raw_response_wrapper( + lists.retrieve, + ) + self.update = async_to_raw_response_wrapper( + lists.update, + ) + self.list = async_to_raw_response_wrapper( + lists.list, + ) + self.delete = async_to_raw_response_wrapper( + lists.delete, + ) + self.restore = async_to_raw_response_wrapper( + lists.restore, + ) + + @cached_property + def subscriptions(self) -> AsyncSubscriptionsResourceWithRawResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + return AsyncSubscriptionsResourceWithRawResponse(self._lists.subscriptions) + + +class ListsResourceWithStreamingResponse: + def __init__(self, lists: ListsResource) -> None: + self._lists = lists + + self.retrieve = to_streamed_response_wrapper( + lists.retrieve, + ) + self.update = to_streamed_response_wrapper( + lists.update, + ) + self.list = to_streamed_response_wrapper( + lists.list, + ) + self.delete = to_streamed_response_wrapper( + lists.delete, + ) + self.restore = to_streamed_response_wrapper( + lists.restore, + ) + + @cached_property + def subscriptions(self) -> SubscriptionsResourceWithStreamingResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + return SubscriptionsResourceWithStreamingResponse(self._lists.subscriptions) + + +class AsyncListsResourceWithStreamingResponse: + def __init__(self, lists: AsyncListsResource) -> None: + self._lists = lists + + self.retrieve = async_to_streamed_response_wrapper( + lists.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + lists.update, + ) + self.list = async_to_streamed_response_wrapper( + lists.list, + ) + self.delete = async_to_streamed_response_wrapper( + lists.delete, + ) + self.restore = async_to_streamed_response_wrapper( + lists.restore, + ) + + @cached_property + def subscriptions(self) -> AsyncSubscriptionsResourceWithStreamingResponse: + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + return AsyncSubscriptionsResourceWithStreamingResponse(self._lists.subscriptions) diff --git a/src/courier/resources/lists/subscriptions.py b/src/courier/resources/lists/subscriptions.py new file mode 100644 index 00000000..a9b5ef55 --- /dev/null +++ b/src/courier/resources/lists/subscriptions.py @@ -0,0 +1,582 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional + +import httpx + +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...types.lists import ( + subscription_add_params, + subscription_list_params, + subscription_subscribe_params, + subscription_subscribe_user_params, +) +from ..._base_client import make_request_options +from ...types.lists.subscription_list_response import SubscriptionListResponse +from ...types.put_subscriptions_recipient_param import PutSubscriptionsRecipientParam +from ...types.shared_params.recipient_preferences import RecipientPreferences + +__all__ = ["SubscriptionsResource", "AsyncSubscriptionsResource"] + + +class SubscriptionsResource(SyncAPIResource): + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + + @cached_property + def with_raw_response(self) -> SubscriptionsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return SubscriptionsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> SubscriptionsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return SubscriptionsResourceWithStreamingResponse(self) + + def list( + self, + list_id: str, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> SubscriptionListResponse: + """ + Returns the users subscribed to a list with paging, each with the preferences + recorded for that subscription. + + Args: + cursor: A unique identifier that allows for fetching the next set of list subscriptions + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + return self._get( + path_template("/lists/{list_id}/subscriptions", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, subscription_list_params.SubscriptionListParams), + ), + cast_to=SubscriptionListResponse, + ) + + def add( + self, + list_id: str, + *, + recipients: Iterable[PutSubscriptionsRecipientParam], + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Subscribes additional users to the list, without modifying existing + subscriptions. If the list does not exist, it will be automatically created. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/lists/{list_id}/subscriptions", list_id=list_id), + body=maybe_transform({"recipients": recipients}, subscription_add_params.SubscriptionAddParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def subscribe( + self, + list_id: str, + *, + recipients: Iterable[PutSubscriptionsRecipientParam], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Subscribes the users to the list, overwriting existing subscriptions. + + If the + list does not exist, it will be automatically created. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/lists/{list_id}/subscriptions", list_id=list_id), + body=maybe_transform({"recipients": recipients}, subscription_subscribe_params.SubscriptionSubscribeParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def subscribe_user( + self, + user_id: str, + *, + list_id: str, + preferences: Optional[RecipientPreferences] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Subscribes one user to a list, creating the list if it does not yet exist. + Optional preferences apply to this subscription only. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/lists/{list_id}/subscriptions/{user_id}", list_id=list_id, user_id=user_id), + body=maybe_transform( + {"preferences": preferences}, subscription_subscribe_user_params.SubscriptionSubscribeUserParams + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def unsubscribe_user( + self, + user_id: str, + *, + list_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Removes one user's subscription to a list, addressed by list id and user id. + + The + user's profile and other subscriptions are separate resources. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/lists/{list_id}/subscriptions/{user_id}", list_id=list_id, user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncSubscriptionsResource(AsyncAPIResource): + """ + Manage static groups of users that you subscribe explicitly, and send to them by list id or list pattern. + """ + + @cached_property + def with_raw_response(self) -> AsyncSubscriptionsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncSubscriptionsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncSubscriptionsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncSubscriptionsResourceWithStreamingResponse(self) + + async def list( + self, + list_id: str, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> SubscriptionListResponse: + """ + Returns the users subscribed to a list with paging, each with the preferences + recorded for that subscription. + + Args: + cursor: A unique identifier that allows for fetching the next set of list subscriptions + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + return await self._get( + path_template("/lists/{list_id}/subscriptions", list_id=list_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"cursor": cursor}, subscription_list_params.SubscriptionListParams), + ), + cast_to=SubscriptionListResponse, + ) + + async def add( + self, + list_id: str, + *, + recipients: Iterable[PutSubscriptionsRecipientParam], + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Subscribes additional users to the list, without modifying existing + subscriptions. If the list does not exist, it will be automatically created. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/lists/{list_id}/subscriptions", list_id=list_id), + body=await async_maybe_transform({"recipients": recipients}, subscription_add_params.SubscriptionAddParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def subscribe( + self, + list_id: str, + *, + recipients: Iterable[PutSubscriptionsRecipientParam], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Subscribes the users to the list, overwriting existing subscriptions. + + If the + list does not exist, it will be automatically created. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/lists/{list_id}/subscriptions", list_id=list_id), + body=await async_maybe_transform( + {"recipients": recipients}, subscription_subscribe_params.SubscriptionSubscribeParams + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def subscribe_user( + self, + user_id: str, + *, + list_id: str, + preferences: Optional[RecipientPreferences] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Subscribes one user to a list, creating the list if it does not yet exist. + Optional preferences apply to this subscription only. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/lists/{list_id}/subscriptions/{user_id}", list_id=list_id, user_id=user_id), + body=await async_maybe_transform( + {"preferences": preferences}, subscription_subscribe_user_params.SubscriptionSubscribeUserParams + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def unsubscribe_user( + self, + user_id: str, + *, + list_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Removes one user's subscription to a list, addressed by list id and user id. + + The + user's profile and other subscriptions are separate resources. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not list_id: + raise ValueError(f"Expected a non-empty value for `list_id` but received {list_id!r}") + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/lists/{list_id}/subscriptions/{user_id}", list_id=list_id, user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class SubscriptionsResourceWithRawResponse: + def __init__(self, subscriptions: SubscriptionsResource) -> None: + self._subscriptions = subscriptions + + self.list = to_raw_response_wrapper( + subscriptions.list, + ) + self.add = to_raw_response_wrapper( + subscriptions.add, + ) + self.subscribe = to_raw_response_wrapper( + subscriptions.subscribe, + ) + self.subscribe_user = to_raw_response_wrapper( + subscriptions.subscribe_user, + ) + self.unsubscribe_user = to_raw_response_wrapper( + subscriptions.unsubscribe_user, + ) + + +class AsyncSubscriptionsResourceWithRawResponse: + def __init__(self, subscriptions: AsyncSubscriptionsResource) -> None: + self._subscriptions = subscriptions + + self.list = async_to_raw_response_wrapper( + subscriptions.list, + ) + self.add = async_to_raw_response_wrapper( + subscriptions.add, + ) + self.subscribe = async_to_raw_response_wrapper( + subscriptions.subscribe, + ) + self.subscribe_user = async_to_raw_response_wrapper( + subscriptions.subscribe_user, + ) + self.unsubscribe_user = async_to_raw_response_wrapper( + subscriptions.unsubscribe_user, + ) + + +class SubscriptionsResourceWithStreamingResponse: + def __init__(self, subscriptions: SubscriptionsResource) -> None: + self._subscriptions = subscriptions + + self.list = to_streamed_response_wrapper( + subscriptions.list, + ) + self.add = to_streamed_response_wrapper( + subscriptions.add, + ) + self.subscribe = to_streamed_response_wrapper( + subscriptions.subscribe, + ) + self.subscribe_user = to_streamed_response_wrapper( + subscriptions.subscribe_user, + ) + self.unsubscribe_user = to_streamed_response_wrapper( + subscriptions.unsubscribe_user, + ) + + +class AsyncSubscriptionsResourceWithStreamingResponse: + def __init__(self, subscriptions: AsyncSubscriptionsResource) -> None: + self._subscriptions = subscriptions + + self.list = async_to_streamed_response_wrapper( + subscriptions.list, + ) + self.add = async_to_streamed_response_wrapper( + subscriptions.add, + ) + self.subscribe = async_to_streamed_response_wrapper( + subscriptions.subscribe, + ) + self.subscribe_user = async_to_streamed_response_wrapper( + subscriptions.subscribe_user, + ) + self.unsubscribe_user = async_to_streamed_response_wrapper( + subscriptions.unsubscribe_user, + ) diff --git a/src/courier/resources/messages.py b/src/courier/resources/messages.py new file mode 100644 index 00000000..9784b2b2 --- /dev/null +++ b/src/courier/resources/messages.py @@ -0,0 +1,736 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +import httpx + +from ..types import message_list_params, message_history_params +from .._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.message_details import MessageDetails +from ..types.message_list_response import MessageListResponse +from ..types.message_resend_response import MessageResendResponse +from ..types.message_content_response import MessageContentResponse +from ..types.message_history_response import MessageHistoryResponse +from ..types.message_retrieve_response import MessageRetrieveResponse + +__all__ = ["MessagesResource", "AsyncMessagesResource"] + + +class MessagesResource(SyncAPIResource): + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + + @cached_property + def with_raw_response(self) -> MessagesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return MessagesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> MessagesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return MessagesResourceWithStreamingResponse(self) + + def retrieve( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageRetrieveResponse: + """ + Returns a sent message's status, recipient, event, and per-provider delivery + detail, with timestamps for enqueued, sent, delivered, opened, and clicked. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return self._get( + path_template("/messages/{message_id}", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageRetrieveResponse, + ) + + def list( + self, + *, + archived: Optional[bool] | Omit = omit, + cursor: Optional[str] | Omit = omit, + enqueued_after: Optional[str] | Omit = omit, + event: Optional[str] | Omit = omit, + list: Optional[str] | Omit = omit, + message_id: Optional[str] | Omit = omit, + notification: Optional[str] | Omit = omit, + provider: SequenceNotStr[Optional[str]] | Omit = omit, + recipient: Optional[str] | Omit = omit, + status: SequenceNotStr[Optional[str]] | Omit = omit, + tag: SequenceNotStr[Optional[str]] | Omit = omit, + tags: Optional[str] | Omit = omit, + tenant_id: Optional[str] | Omit = omit, + trace_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageListResponse: + """ + Returns previously sent messages, most recent first, each carrying its status, + recipient, channel, and provider. Paged by cursor. + + Args: + archived: A boolean value that indicates whether archived messages should be included in + the response. + + cursor: A unique identifier that allows for fetching the next set of messages. + + enqueued_after: The enqueued datetime of a message to filter out messages received before. + + event: A unique identifier representing the event that was used to send the event. + + list: A unique identifier representing the list the message was sent to. + + message_id: A unique identifier representing the message_id returned from either /send or + /send/list. + + notification: A unique identifier representing the notification that was used to send the + event. + + provider: The key assocated to the provider you want to filter on. E.g., sendgrid, inbox, + twilio, slack, msteams, etc. Allows multiple values to be set in query + parameters. + + recipient: A unique identifier representing the recipient associated with the requested + profile. + + status: An indicator of the current status of the message. Allows multiple values to be + set in query parameters. + + tag: A tag placed in the metadata.tags during a notification send. Allows multiple + values to be set in query parameters. + + tags: A comma delimited list of 'tags'. Messages will be returned if they match any of + the tags passed in. + + tenant_id: Messages sent with the context of a Tenant + + trace_id: The unique identifier used to trace the requests + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/messages", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "archived": archived, + "cursor": cursor, + "enqueued_after": enqueued_after, + "event": event, + "list": list, + "message_id": message_id, + "notification": notification, + "provider": provider, + "recipient": recipient, + "status": status, + "tag": tag, + "tags": tags, + "tenant_id": tenant_id, + "trace_id": trace_id, + }, + message_list_params.MessageListParams, + ), + ), + cast_to=MessageListResponse, + ) + + def cancel( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageDetails: + """ + Cancels a message that is still in the delivery pipeline and returns the message + record with its resulting canceled or failed status. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return self._post( + path_template("/messages/{message_id}/cancel", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageDetails, + ) + + def content( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageContentResponse: + """ + Returns the rendered content Courier delivered for a message, broken out per + channel, to confirm what the recipient received. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return self._get( + path_template("/messages/{message_id}/output", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageContentResponse, + ) + + def history( + self, + message_id: str, + *, + type: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageHistoryResponse: + """ + Returns the ordered event history for a sent message, one entry per status + transition with its timestamp. + + Args: + type: A supported Message History type that will filter the events returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return self._get( + path_template("/messages/{message_id}/history", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"type": type}, message_history_params.MessageHistoryParams), + ), + cast_to=MessageHistoryResponse, + ) + + def resend( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageResendResponse: + """ + Resends a previously sent message to the same recipient and content, returning a + new messageId. The original send request is not modified. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return self._post( + path_template("/messages/{message_id}/resend", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageResendResponse, + ) + + +class AsyncMessagesResource(AsyncAPIResource): + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + + @cached_property + def with_raw_response(self) -> AsyncMessagesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncMessagesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncMessagesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncMessagesResourceWithStreamingResponse(self) + + async def retrieve( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageRetrieveResponse: + """ + Returns a sent message's status, recipient, event, and per-provider delivery + detail, with timestamps for enqueued, sent, delivered, opened, and clicked. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return await self._get( + path_template("/messages/{message_id}", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageRetrieveResponse, + ) + + async def list( + self, + *, + archived: Optional[bool] | Omit = omit, + cursor: Optional[str] | Omit = omit, + enqueued_after: Optional[str] | Omit = omit, + event: Optional[str] | Omit = omit, + list: Optional[str] | Omit = omit, + message_id: Optional[str] | Omit = omit, + notification: Optional[str] | Omit = omit, + provider: SequenceNotStr[Optional[str]] | Omit = omit, + recipient: Optional[str] | Omit = omit, + status: SequenceNotStr[Optional[str]] | Omit = omit, + tag: SequenceNotStr[Optional[str]] | Omit = omit, + tags: Optional[str] | Omit = omit, + tenant_id: Optional[str] | Omit = omit, + trace_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageListResponse: + """ + Returns previously sent messages, most recent first, each carrying its status, + recipient, channel, and provider. Paged by cursor. + + Args: + archived: A boolean value that indicates whether archived messages should be included in + the response. + + cursor: A unique identifier that allows for fetching the next set of messages. + + enqueued_after: The enqueued datetime of a message to filter out messages received before. + + event: A unique identifier representing the event that was used to send the event. + + list: A unique identifier representing the list the message was sent to. + + message_id: A unique identifier representing the message_id returned from either /send or + /send/list. + + notification: A unique identifier representing the notification that was used to send the + event. + + provider: The key assocated to the provider you want to filter on. E.g., sendgrid, inbox, + twilio, slack, msteams, etc. Allows multiple values to be set in query + parameters. + + recipient: A unique identifier representing the recipient associated with the requested + profile. + + status: An indicator of the current status of the message. Allows multiple values to be + set in query parameters. + + tag: A tag placed in the metadata.tags during a notification send. Allows multiple + values to be set in query parameters. + + tags: A comma delimited list of 'tags'. Messages will be returned if they match any of + the tags passed in. + + tenant_id: Messages sent with the context of a Tenant + + trace_id: The unique identifier used to trace the requests + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/messages", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "archived": archived, + "cursor": cursor, + "enqueued_after": enqueued_after, + "event": event, + "list": list, + "message_id": message_id, + "notification": notification, + "provider": provider, + "recipient": recipient, + "status": status, + "tag": tag, + "tags": tags, + "tenant_id": tenant_id, + "trace_id": trace_id, + }, + message_list_params.MessageListParams, + ), + ), + cast_to=MessageListResponse, + ) + + async def cancel( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageDetails: + """ + Cancels a message that is still in the delivery pipeline and returns the message + record with its resulting canceled or failed status. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return await self._post( + path_template("/messages/{message_id}/cancel", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageDetails, + ) + + async def content( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageContentResponse: + """ + Returns the rendered content Courier delivered for a message, broken out per + channel, to confirm what the recipient received. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return await self._get( + path_template("/messages/{message_id}/output", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageContentResponse, + ) + + async def history( + self, + message_id: str, + *, + type: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageHistoryResponse: + """ + Returns the ordered event history for a sent message, one entry per status + transition with its timestamp. + + Args: + type: A supported Message History type that will filter the events returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return await self._get( + path_template("/messages/{message_id}/history", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"type": type}, message_history_params.MessageHistoryParams), + ), + cast_to=MessageHistoryResponse, + ) + + async def resend( + self, + message_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> MessageResendResponse: + """ + Resends a previously sent message to the same recipient and content, returning a + new messageId. The original send request is not modified. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + return await self._post( + path_template("/messages/{message_id}/resend", message_id=message_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageResendResponse, + ) + + +class MessagesResourceWithRawResponse: + def __init__(self, messages: MessagesResource) -> None: + self._messages = messages + + self.retrieve = to_raw_response_wrapper( + messages.retrieve, + ) + self.list = to_raw_response_wrapper( + messages.list, + ) + self.cancel = to_raw_response_wrapper( + messages.cancel, + ) + self.content = to_raw_response_wrapper( + messages.content, + ) + self.history = to_raw_response_wrapper( + messages.history, + ) + self.resend = to_raw_response_wrapper( + messages.resend, + ) + + +class AsyncMessagesResourceWithRawResponse: + def __init__(self, messages: AsyncMessagesResource) -> None: + self._messages = messages + + self.retrieve = async_to_raw_response_wrapper( + messages.retrieve, + ) + self.list = async_to_raw_response_wrapper( + messages.list, + ) + self.cancel = async_to_raw_response_wrapper( + messages.cancel, + ) + self.content = async_to_raw_response_wrapper( + messages.content, + ) + self.history = async_to_raw_response_wrapper( + messages.history, + ) + self.resend = async_to_raw_response_wrapper( + messages.resend, + ) + + +class MessagesResourceWithStreamingResponse: + def __init__(self, messages: MessagesResource) -> None: + self._messages = messages + + self.retrieve = to_streamed_response_wrapper( + messages.retrieve, + ) + self.list = to_streamed_response_wrapper( + messages.list, + ) + self.cancel = to_streamed_response_wrapper( + messages.cancel, + ) + self.content = to_streamed_response_wrapper( + messages.content, + ) + self.history = to_streamed_response_wrapper( + messages.history, + ) + self.resend = to_streamed_response_wrapper( + messages.resend, + ) + + +class AsyncMessagesResourceWithStreamingResponse: + def __init__(self, messages: AsyncMessagesResource) -> None: + self._messages = messages + + self.retrieve = async_to_streamed_response_wrapper( + messages.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + messages.list, + ) + self.cancel = async_to_streamed_response_wrapper( + messages.cancel, + ) + self.content = async_to_streamed_response_wrapper( + messages.content, + ) + self.history = async_to_streamed_response_wrapper( + messages.history, + ) + self.resend = async_to_streamed_response_wrapper( + messages.resend, + ) diff --git a/src/courier/resources/notifications/__init__.py b/src/courier/resources/notifications/__init__.py new file mode 100644 index 00000000..75626ebf --- /dev/null +++ b/src/courier/resources/notifications/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .checks import ( + ChecksResource, + AsyncChecksResource, + ChecksResourceWithRawResponse, + AsyncChecksResourceWithRawResponse, + ChecksResourceWithStreamingResponse, + AsyncChecksResourceWithStreamingResponse, +) +from .notifications import ( + NotificationsResource, + AsyncNotificationsResource, + NotificationsResourceWithRawResponse, + AsyncNotificationsResourceWithRawResponse, + NotificationsResourceWithStreamingResponse, + AsyncNotificationsResourceWithStreamingResponse, +) + +__all__ = [ + "ChecksResource", + "AsyncChecksResource", + "ChecksResourceWithRawResponse", + "AsyncChecksResourceWithRawResponse", + "ChecksResourceWithStreamingResponse", + "AsyncChecksResourceWithStreamingResponse", + "NotificationsResource", + "AsyncNotificationsResource", + "NotificationsResourceWithRawResponse", + "AsyncNotificationsResourceWithRawResponse", + "NotificationsResourceWithStreamingResponse", + "AsyncNotificationsResourceWithStreamingResponse", +] diff --git a/src/courier/resources/notifications/checks.py b/src/courier/resources/notifications/checks.py new file mode 100644 index 00000000..d26396c5 --- /dev/null +++ b/src/courier/resources/notifications/checks.py @@ -0,0 +1,365 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable + +import httpx + +from ..._types import Body, Query, Headers, NoneType, NotGiven, not_given +from ..._utils import path_template, maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.notifications import check_update_params +from ...types.base_check_param import BaseCheckParam +from ...types.notifications.check_list_response import CheckListResponse +from ...types.notifications.check_update_response import CheckUpdateResponse + +__all__ = ["ChecksResource", "AsyncChecksResource"] + + +class ChecksResource(SyncAPIResource): + """ + Create, update, version, publish, and localize notification templates and their content. + """ + + @cached_property + def with_raw_response(self) -> ChecksResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return ChecksResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ChecksResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return ChecksResourceWithStreamingResponse(self) + + def update( + self, + submission_id: str, + *, + id: str, + checks: Iterable[BaseCheckParam], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CheckUpdateResponse: + """ + Replaces the approval checks on a template submission with the complete set + supplied in the request body. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not submission_id: + raise ValueError(f"Expected a non-empty value for `submission_id` but received {submission_id!r}") + return self._put( + path_template("/notifications/{id}/{submission_id}/checks", id=id, submission_id=submission_id), + body=maybe_transform({"checks": checks}, check_update_params.CheckUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=CheckUpdateResponse, + ) + + def list( + self, + submission_id: str, + *, + id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CheckListResponse: + """ + Returns the approval checks recorded for a template submission, each with its + pass or fail result. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not submission_id: + raise ValueError(f"Expected a non-empty value for `submission_id` but received {submission_id!r}") + return self._get( + path_template("/notifications/{id}/{submission_id}/checks", id=id, submission_id=submission_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=CheckListResponse, + ) + + def delete( + self, + submission_id: str, + *, + id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Cancels a pending template submission, withdrawing it from the approval + workflow. + + The template stays in draft and can be resubmitted later. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not submission_id: + raise ValueError(f"Expected a non-empty value for `submission_id` but received {submission_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/notifications/{id}/{submission_id}/checks", id=id, submission_id=submission_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncChecksResource(AsyncAPIResource): + """ + Create, update, version, publish, and localize notification templates and their content. + """ + + @cached_property + def with_raw_response(self) -> AsyncChecksResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncChecksResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncChecksResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncChecksResourceWithStreamingResponse(self) + + async def update( + self, + submission_id: str, + *, + id: str, + checks: Iterable[BaseCheckParam], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CheckUpdateResponse: + """ + Replaces the approval checks on a template submission with the complete set + supplied in the request body. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not submission_id: + raise ValueError(f"Expected a non-empty value for `submission_id` but received {submission_id!r}") + return await self._put( + path_template("/notifications/{id}/{submission_id}/checks", id=id, submission_id=submission_id), + body=await async_maybe_transform({"checks": checks}, check_update_params.CheckUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=CheckUpdateResponse, + ) + + async def list( + self, + submission_id: str, + *, + id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CheckListResponse: + """ + Returns the approval checks recorded for a template submission, each with its + pass or fail result. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not submission_id: + raise ValueError(f"Expected a non-empty value for `submission_id` but received {submission_id!r}") + return await self._get( + path_template("/notifications/{id}/{submission_id}/checks", id=id, submission_id=submission_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=CheckListResponse, + ) + + async def delete( + self, + submission_id: str, + *, + id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Cancels a pending template submission, withdrawing it from the approval + workflow. + + The template stays in draft and can be resubmitted later. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not submission_id: + raise ValueError(f"Expected a non-empty value for `submission_id` but received {submission_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/notifications/{id}/{submission_id}/checks", id=id, submission_id=submission_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class ChecksResourceWithRawResponse: + def __init__(self, checks: ChecksResource) -> None: + self._checks = checks + + self.update = to_raw_response_wrapper( + checks.update, + ) + self.list = to_raw_response_wrapper( + checks.list, + ) + self.delete = to_raw_response_wrapper( + checks.delete, + ) + + +class AsyncChecksResourceWithRawResponse: + def __init__(self, checks: AsyncChecksResource) -> None: + self._checks = checks + + self.update = async_to_raw_response_wrapper( + checks.update, + ) + self.list = async_to_raw_response_wrapper( + checks.list, + ) + self.delete = async_to_raw_response_wrapper( + checks.delete, + ) + + +class ChecksResourceWithStreamingResponse: + def __init__(self, checks: ChecksResource) -> None: + self._checks = checks + + self.update = to_streamed_response_wrapper( + checks.update, + ) + self.list = to_streamed_response_wrapper( + checks.list, + ) + self.delete = to_streamed_response_wrapper( + checks.delete, + ) + + +class AsyncChecksResourceWithStreamingResponse: + def __init__(self, checks: AsyncChecksResource) -> None: + self._checks = checks + + self.update = async_to_streamed_response_wrapper( + checks.update, + ) + self.list = async_to_streamed_response_wrapper( + checks.list, + ) + self.delete = async_to_streamed_response_wrapper( + checks.delete, + ) diff --git a/src/courier/resources/notifications/notifications.py b/src/courier/resources/notifications/notifications.py new file mode 100644 index 00000000..b2c575ed --- /dev/null +++ b/src/courier/resources/notifications/notifications.py @@ -0,0 +1,1480 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Any, Dict, Iterable, Optional, cast +from typing_extensions import Literal + +import httpx + +from .checks import ( + ChecksResource, + AsyncChecksResource, + ChecksResourceWithRawResponse, + AsyncChecksResourceWithRawResponse, + ChecksResourceWithStreamingResponse, + AsyncChecksResourceWithStreamingResponse, +) +from ...types import ( + NotificationTemplateState, + notification_list_params, + notification_create_params, + notification_publish_params, + notification_replace_params, + notification_retrieve_params, + notification_put_locale_params, + notification_put_content_params, + notification_put_element_params, + notification_list_versions_params, + notification_retrieve_content_params, +) +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, SequenceNotStr, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.notification_list_response import NotificationListResponse +from ...types.notification_template_state import NotificationTemplateState +from ...types.notification_template_response import NotificationTemplateResponse +from ...types.notification_content_mutation_response import NotificationContentMutationResponse +from ...types.notification_retrieve_content_response import NotificationRetrieveContentResponse +from ...types.notification_template_write_payload_param import NotificationTemplateWritePayloadParam +from ...types.notification_template_version_list_response import NotificationTemplateVersionListResponse + +__all__ = ["NotificationsResource", "AsyncNotificationsResource"] + + +class NotificationsResource(SyncAPIResource): + """ + Create, update, version, publish, and localize notification templates and their content. + """ + + @cached_property + def checks(self) -> ChecksResource: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + return ChecksResource(self._client) + + @cached_property + def with_raw_response(self) -> NotificationsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return NotificationsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> NotificationsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return NotificationsResourceWithStreamingResponse(self) + + def create( + self, + *, + notification: NotificationTemplateWritePayloadParam, + state: Literal["DRAFT", "PUBLISHED"] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """Create a notification template. + + Requires all fields in the notification object. + Templates are created in draft state by default. + + Args: + notification: Template fields accepted in POST and PUT request bodies, nested under a + `notification` key. + + state: Template state after creation. Case-insensitive input, normalized to uppercase + in the response. Defaults to "DRAFT". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/notifications", + body=maybe_transform( + { + "notification": notification, + "state": state, + }, + notification_create_params.NotificationCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateResponse, + ) + + def retrieve( + self, + id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """Retrieve a notification template by ID. + + Returns the published version by + default. Pass version=draft to retrieve an unpublished template. + + Args: + version: Version to retrieve. One of "draft", "published", or a version string like + "v001". Defaults to "published". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + path_template("/notifications/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"version": version}, notification_retrieve_params.NotificationRetrieveParams), + ), + cast_to=NotificationTemplateResponse, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + event_id: str | Omit = omit, + notes: Optional[bool] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationListResponse: + """Lists the workspace's notification templates. + + Each carries a name, tags, brand, + routing, and its draft or published state. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + event_id: Filter to templates linked to this event map ID. + + notes: Include template notes in the response. Only applies to legacy templates. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/notifications", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "event_id": event_id, + "notes": notes, + }, + notification_list_params.NotificationListParams, + ), + ), + cast_to=NotificationListResponse, + ) + + def archive( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives a notification template, preventing new sends from referencing it. + + The + template stays retrievable for its version history. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/notifications/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def duplicate( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """ + Copies a notification template within the same workspace and environment, + appending " COPY" to the title. The copy is standalone and independently + editable. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._post( + path_template("/notifications/{id}/duplicate", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateResponse, + ) + + def list_versions( + self, + id: str, + *, + cursor: str | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateVersionListResponse: + """ + Returns a notification template's published versions, most recent first, for + comparison or rollback. Paged. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of versions to return per page. Default 10, max 10. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + path_template("/notifications/{id}/versions", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + notification_list_versions_params.NotificationListVersionsParams, + ), + ), + cast_to=NotificationTemplateVersionListResponse, + ) + + def publish( + self, + id: str, + *, + version: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Publish a notification template. + + Publishes the current draft by default. Pass a + version in the request body to publish a specific historical version. + + Args: + version: Historical version to publish (e.g. "v001"). Omit to publish the current draft. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/notifications/{id}/publish", id=id), + body=maybe_transform({"version": version}, notification_publish_params.NotificationPublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def put_content( + self, + id: str, + *, + content: notification_put_content_params.Content, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """Replaces all Elemental content in a template, overwriting every existing + element. + + Supported for V2 templates only, not V1 blocks and channels. + + Args: + content: Elemental content payload. The server defaults `version` when omitted. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._put( + path_template("/notifications/{id}/content", id=id), + body=maybe_transform( + { + "content": content, + "state": state, + }, + notification_put_content_params.NotificationPutContentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + def put_element( + self, + element_id: str, + *, + id: str, + type: str, + channels: SequenceNotStr[str] | Omit = omit, + data: Dict[str, object] | Omit = omit, + if_: str | Omit = omit, + loop: str | Omit = omit, + ref: str | Omit = omit, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """ + Replaces one Elemental element in a template, addressed by its element id. + Supported for V2 templates only, not V1 blocks and channels. + + Args: + type: Element type (text, meta, action, image, etc.). + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not element_id: + raise ValueError(f"Expected a non-empty value for `element_id` but received {element_id!r}") + return self._put( + path_template("/notifications/{id}/elements/{element_id}", id=id, element_id=element_id), + body=maybe_transform( + { + "type": type, + "channels": channels, + "data": data, + "if_": if_, + "loop": loop, + "ref": ref, + "state": state, + }, + notification_put_element_params.NotificationPutElementParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + def put_locale( + self, + locale_id: str, + *, + id: str, + elements: Iterable[notification_put_locale_params.Element], + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """Sets locale-specific content overrides for a template. + + Each override must + reference an element that already exists in the default content. + + Args: + elements: Elements with locale-specific content overrides. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not locale_id: + raise ValueError(f"Expected a non-empty value for `locale_id` but received {locale_id!r}") + return self._put( + path_template("/notifications/{id}/locales/{locale_id}", id=id, locale_id=locale_id), + body=maybe_transform( + { + "elements": elements, + "state": state, + }, + notification_put_locale_params.NotificationPutLocaleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + def replace( + self, + id: str, + *, + notification: NotificationTemplateWritePayloadParam, + state: Literal["DRAFT", "PUBLISHED"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """ + Replaces a notification template in full, so send every field rather than only + the ones you want changed. Publish separately to make it live. + + Args: + notification: Template fields accepted in POST and PUT request bodies, nested under a + `notification` key. + + state: Template state after update. Case-insensitive input, normalized to uppercase in + the response. Defaults to "DRAFT". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._put( + path_template("/notifications/{id}", id=id), + body=maybe_transform( + { + "notification": notification, + "state": state, + }, + notification_replace_params.NotificationReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateResponse, + ) + + def retrieve_content( + self, + id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationRetrieveContentResponse: + """Returns a template's content and checksum. + + V2 templates return Elemental + elements, while V1 templates return blocks and channels instead. + + Args: + version: Accepts `draft`, `published`, or a version string (e.g., `v001`). Defaults to + `published`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return cast( + NotificationRetrieveContentResponse, + self._get( + path_template("/notifications/{id}/content", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"version": version}, notification_retrieve_content_params.NotificationRetrieveContentParams + ), + ), + cast_to=cast( + Any, NotificationRetrieveContentResponse + ), # Union types cannot be passed in as arguments in the type system + ), + ) + + +class AsyncNotificationsResource(AsyncAPIResource): + """ + Create, update, version, publish, and localize notification templates and their content. + """ + + @cached_property + def checks(self) -> AsyncChecksResource: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + return AsyncChecksResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncNotificationsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncNotificationsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncNotificationsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncNotificationsResourceWithStreamingResponse(self) + + async def create( + self, + *, + notification: NotificationTemplateWritePayloadParam, + state: Literal["DRAFT", "PUBLISHED"] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """Create a notification template. + + Requires all fields in the notification object. + Templates are created in draft state by default. + + Args: + notification: Template fields accepted in POST and PUT request bodies, nested under a + `notification` key. + + state: Template state after creation. Case-insensitive input, normalized to uppercase + in the response. Defaults to "DRAFT". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/notifications", + body=await async_maybe_transform( + { + "notification": notification, + "state": state, + }, + notification_create_params.NotificationCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateResponse, + ) + + async def retrieve( + self, + id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """Retrieve a notification template by ID. + + Returns the published version by + default. Pass version=draft to retrieve an unpublished template. + + Args: + version: Version to retrieve. One of "draft", "published", or a version string like + "v001". Defaults to "published". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + path_template("/notifications/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"version": version}, notification_retrieve_params.NotificationRetrieveParams + ), + ), + cast_to=NotificationTemplateResponse, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + event_id: str | Omit = omit, + notes: Optional[bool] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationListResponse: + """Lists the workspace's notification templates. + + Each carries a name, tags, brand, + routing, and its draft or published state. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + event_id: Filter to templates linked to this event map ID. + + notes: Include template notes in the response. Only applies to legacy templates. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/notifications", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "event_id": event_id, + "notes": notes, + }, + notification_list_params.NotificationListParams, + ), + ), + cast_to=NotificationListResponse, + ) + + async def archive( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives a notification template, preventing new sends from referencing it. + + The + template stays retrievable for its version history. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/notifications/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def duplicate( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """ + Copies a notification template within the same workspace and environment, + appending " COPY" to the title. The copy is standalone and independently + editable. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._post( + path_template("/notifications/{id}/duplicate", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateResponse, + ) + + async def list_versions( + self, + id: str, + *, + cursor: str | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateVersionListResponse: + """ + Returns a notification template's published versions, most recent first, for + comparison or rollback. Paged. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of versions to return per page. Default 10, max 10. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + path_template("/notifications/{id}/versions", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + notification_list_versions_params.NotificationListVersionsParams, + ), + ), + cast_to=NotificationTemplateVersionListResponse, + ) + + async def publish( + self, + id: str, + *, + version: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Publish a notification template. + + Publishes the current draft by default. Pass a + version in the request body to publish a specific historical version. + + Args: + version: Historical version to publish (e.g. "v001"). Omit to publish the current draft. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/notifications/{id}/publish", id=id), + body=await async_maybe_transform( + {"version": version}, notification_publish_params.NotificationPublishParams + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def put_content( + self, + id: str, + *, + content: notification_put_content_params.Content, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """Replaces all Elemental content in a template, overwriting every existing + element. + + Supported for V2 templates only, not V1 blocks and channels. + + Args: + content: Elemental content payload. The server defaults `version` when omitted. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._put( + path_template("/notifications/{id}/content", id=id), + body=await async_maybe_transform( + { + "content": content, + "state": state, + }, + notification_put_content_params.NotificationPutContentParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + async def put_element( + self, + element_id: str, + *, + id: str, + type: str, + channels: SequenceNotStr[str] | Omit = omit, + data: Dict[str, object] | Omit = omit, + if_: str | Omit = omit, + loop: str | Omit = omit, + ref: str | Omit = omit, + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """ + Replaces one Elemental element in a template, addressed by its element id. + Supported for V2 templates only, not V1 blocks and channels. + + Args: + type: Element type (text, meta, action, image, etc.). + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not element_id: + raise ValueError(f"Expected a non-empty value for `element_id` but received {element_id!r}") + return await self._put( + path_template("/notifications/{id}/elements/{element_id}", id=id, element_id=element_id), + body=await async_maybe_transform( + { + "type": type, + "channels": channels, + "data": data, + "if_": if_, + "loop": loop, + "ref": ref, + "state": state, + }, + notification_put_element_params.NotificationPutElementParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + async def put_locale( + self, + locale_id: str, + *, + id: str, + elements: Iterable[notification_put_locale_params.Element], + state: NotificationTemplateState | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationContentMutationResponse: + """Sets locale-specific content overrides for a template. + + Each override must + reference an element that already exists in the default content. + + Args: + elements: Elements with locale-specific content overrides. + + state: Template state. Defaults to `DRAFT`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + if not locale_id: + raise ValueError(f"Expected a non-empty value for `locale_id` but received {locale_id!r}") + return await self._put( + path_template("/notifications/{id}/locales/{locale_id}", id=id, locale_id=locale_id), + body=await async_maybe_transform( + { + "elements": elements, + "state": state, + }, + notification_put_locale_params.NotificationPutLocaleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationContentMutationResponse, + ) + + async def replace( + self, + id: str, + *, + notification: NotificationTemplateWritePayloadParam, + state: Literal["DRAFT", "PUBLISHED"] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationTemplateResponse: + """ + Replaces a notification template in full, so send every field rather than only + the ones you want changed. Publish separately to make it live. + + Args: + notification: Template fields accepted in POST and PUT request bodies, nested under a + `notification` key. + + state: Template state after update. Case-insensitive input, normalized to uppercase in + the response. Defaults to "DRAFT". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._put( + path_template("/notifications/{id}", id=id), + body=await async_maybe_transform( + { + "notification": notification, + "state": state, + }, + notification_replace_params.NotificationReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NotificationTemplateResponse, + ) + + async def retrieve_content( + self, + id: str, + *, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> NotificationRetrieveContentResponse: + """Returns a template's content and checksum. + + V2 templates return Elemental + elements, while V1 templates return blocks and channels instead. + + Args: + version: Accepts `draft`, `published`, or a version string (e.g., `v001`). Defaults to + `published`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return cast( + NotificationRetrieveContentResponse, + await self._get( + path_template("/notifications/{id}/content", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"version": version}, notification_retrieve_content_params.NotificationRetrieveContentParams + ), + ), + cast_to=cast( + Any, NotificationRetrieveContentResponse + ), # Union types cannot be passed in as arguments in the type system + ), + ) + + +class NotificationsResourceWithRawResponse: + def __init__(self, notifications: NotificationsResource) -> None: + self._notifications = notifications + + self.create = to_raw_response_wrapper( + notifications.create, + ) + self.retrieve = to_raw_response_wrapper( + notifications.retrieve, + ) + self.list = to_raw_response_wrapper( + notifications.list, + ) + self.archive = to_raw_response_wrapper( + notifications.archive, + ) + self.duplicate = to_raw_response_wrapper( + notifications.duplicate, + ) + self.list_versions = to_raw_response_wrapper( + notifications.list_versions, + ) + self.publish = to_raw_response_wrapper( + notifications.publish, + ) + self.put_content = to_raw_response_wrapper( + notifications.put_content, + ) + self.put_element = to_raw_response_wrapper( + notifications.put_element, + ) + self.put_locale = to_raw_response_wrapper( + notifications.put_locale, + ) + self.replace = to_raw_response_wrapper( + notifications.replace, + ) + self.retrieve_content = to_raw_response_wrapper( + notifications.retrieve_content, + ) + + @cached_property + def checks(self) -> ChecksResourceWithRawResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + return ChecksResourceWithRawResponse(self._notifications.checks) + + +class AsyncNotificationsResourceWithRawResponse: + def __init__(self, notifications: AsyncNotificationsResource) -> None: + self._notifications = notifications + + self.create = async_to_raw_response_wrapper( + notifications.create, + ) + self.retrieve = async_to_raw_response_wrapper( + notifications.retrieve, + ) + self.list = async_to_raw_response_wrapper( + notifications.list, + ) + self.archive = async_to_raw_response_wrapper( + notifications.archive, + ) + self.duplicate = async_to_raw_response_wrapper( + notifications.duplicate, + ) + self.list_versions = async_to_raw_response_wrapper( + notifications.list_versions, + ) + self.publish = async_to_raw_response_wrapper( + notifications.publish, + ) + self.put_content = async_to_raw_response_wrapper( + notifications.put_content, + ) + self.put_element = async_to_raw_response_wrapper( + notifications.put_element, + ) + self.put_locale = async_to_raw_response_wrapper( + notifications.put_locale, + ) + self.replace = async_to_raw_response_wrapper( + notifications.replace, + ) + self.retrieve_content = async_to_raw_response_wrapper( + notifications.retrieve_content, + ) + + @cached_property + def checks(self) -> AsyncChecksResourceWithRawResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + return AsyncChecksResourceWithRawResponse(self._notifications.checks) + + +class NotificationsResourceWithStreamingResponse: + def __init__(self, notifications: NotificationsResource) -> None: + self._notifications = notifications + + self.create = to_streamed_response_wrapper( + notifications.create, + ) + self.retrieve = to_streamed_response_wrapper( + notifications.retrieve, + ) + self.list = to_streamed_response_wrapper( + notifications.list, + ) + self.archive = to_streamed_response_wrapper( + notifications.archive, + ) + self.duplicate = to_streamed_response_wrapper( + notifications.duplicate, + ) + self.list_versions = to_streamed_response_wrapper( + notifications.list_versions, + ) + self.publish = to_streamed_response_wrapper( + notifications.publish, + ) + self.put_content = to_streamed_response_wrapper( + notifications.put_content, + ) + self.put_element = to_streamed_response_wrapper( + notifications.put_element, + ) + self.put_locale = to_streamed_response_wrapper( + notifications.put_locale, + ) + self.replace = to_streamed_response_wrapper( + notifications.replace, + ) + self.retrieve_content = to_streamed_response_wrapper( + notifications.retrieve_content, + ) + + @cached_property + def checks(self) -> ChecksResourceWithStreamingResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + return ChecksResourceWithStreamingResponse(self._notifications.checks) + + +class AsyncNotificationsResourceWithStreamingResponse: + def __init__(self, notifications: AsyncNotificationsResource) -> None: + self._notifications = notifications + + self.create = async_to_streamed_response_wrapper( + notifications.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + notifications.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + notifications.list, + ) + self.archive = async_to_streamed_response_wrapper( + notifications.archive, + ) + self.duplicate = async_to_streamed_response_wrapper( + notifications.duplicate, + ) + self.list_versions = async_to_streamed_response_wrapper( + notifications.list_versions, + ) + self.publish = async_to_streamed_response_wrapper( + notifications.publish, + ) + self.put_content = async_to_streamed_response_wrapper( + notifications.put_content, + ) + self.put_element = async_to_streamed_response_wrapper( + notifications.put_element, + ) + self.put_locale = async_to_streamed_response_wrapper( + notifications.put_locale, + ) + self.replace = async_to_streamed_response_wrapper( + notifications.replace, + ) + self.retrieve_content = async_to_streamed_response_wrapper( + notifications.retrieve_content, + ) + + @cached_property + def checks(self) -> AsyncChecksResourceWithStreamingResponse: + """ + Create, update, version, publish, and localize notification templates and their content. + """ + return AsyncChecksResourceWithStreamingResponse(self._notifications.checks) diff --git a/src/courier/resources/profiles/__init__.py b/src/courier/resources/profiles/__init__.py new file mode 100644 index 00000000..1cdcb364 --- /dev/null +++ b/src/courier/resources/profiles/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .lists import ( + ListsResource, + AsyncListsResource, + ListsResourceWithRawResponse, + AsyncListsResourceWithRawResponse, + ListsResourceWithStreamingResponse, + AsyncListsResourceWithStreamingResponse, +) +from .profiles import ( + ProfilesResource, + AsyncProfilesResource, + ProfilesResourceWithRawResponse, + AsyncProfilesResourceWithRawResponse, + ProfilesResourceWithStreamingResponse, + AsyncProfilesResourceWithStreamingResponse, +) + +__all__ = [ + "ListsResource", + "AsyncListsResource", + "ListsResourceWithRawResponse", + "AsyncListsResourceWithRawResponse", + "ListsResourceWithStreamingResponse", + "AsyncListsResourceWithStreamingResponse", + "ProfilesResource", + "AsyncProfilesResource", + "ProfilesResourceWithRawResponse", + "AsyncProfilesResourceWithRawResponse", + "ProfilesResourceWithStreamingResponse", + "AsyncProfilesResourceWithStreamingResponse", +] diff --git a/src/courier/resources/profiles/lists.py b/src/courier/resources/profiles/lists.py new file mode 100644 index 00000000..7e2c040f --- /dev/null +++ b/src/courier/resources/profiles/lists.py @@ -0,0 +1,384 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional + +import httpx + +from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.profiles import list_retrieve_params, list_subscribe_params +from ...types.profiles.list_delete_response import ListDeleteResponse +from ...types.profiles.list_retrieve_response import ListRetrieveResponse +from ...types.profiles.list_subscribe_response import ListSubscribeResponse +from ...types.subscribe_to_lists_request_item_param import SubscribeToListsRequestItemParam + +__all__ = ["ListsResource", "AsyncListsResource"] + + +class ListsResource(SyncAPIResource): + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + + @cached_property + def with_raw_response(self) -> ListsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return ListsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ListsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return ListsResourceWithStreamingResponse(self) + + def retrieve( + self, + user_id: str, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListRetrieveResponse: + """Returns the lists a user is subscribed to, with paging. + + Use it to check what a + recipient will receive before sending to a list. + + Args: + cursor: A unique identifier that allows for fetching the next set of message statuses. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._get( + path_template("/profiles/{user_id}/lists", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, list_retrieve_params.ListRetrieveParams), + ), + cast_to=ListRetrieveResponse, + ) + + def delete( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListDeleteResponse: + """Removes every list subscription for a user at once. + + Their profile and + preferences are untouched, so this only affects list-targeted sends. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._delete( + path_template("/profiles/{user_id}/lists", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ListDeleteResponse, + ) + + def subscribe( + self, + user_id: str, + *, + lists: Iterable[SubscribeToListsRequestItemParam], + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListSubscribeResponse: + """ + Subscribes a user to one or more lists, creating any list that does not yet + exist. Optional preferences apply to each subscription. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/profiles/{user_id}/lists", user_id=user_id), + body=maybe_transform({"lists": lists}, list_subscribe_params.ListSubscribeParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ListSubscribeResponse, + ) + + +class AsyncListsResource(AsyncAPIResource): + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + + @cached_property + def with_raw_response(self) -> AsyncListsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncListsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncListsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncListsResourceWithStreamingResponse(self) + + async def retrieve( + self, + user_id: str, + *, + cursor: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListRetrieveResponse: + """Returns the lists a user is subscribed to, with paging. + + Use it to check what a + recipient will receive before sending to a list. + + Args: + cursor: A unique identifier that allows for fetching the next set of message statuses. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._get( + path_template("/profiles/{user_id}/lists", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"cursor": cursor}, list_retrieve_params.ListRetrieveParams), + ), + cast_to=ListRetrieveResponse, + ) + + async def delete( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListDeleteResponse: + """Removes every list subscription for a user at once. + + Their profile and + preferences are untouched, so this only affects list-targeted sends. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._delete( + path_template("/profiles/{user_id}/lists", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ListDeleteResponse, + ) + + async def subscribe( + self, + user_id: str, + *, + lists: Iterable[SubscribeToListsRequestItemParam], + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ListSubscribeResponse: + """ + Subscribes a user to one or more lists, creating any list that does not yet + exist. Optional preferences apply to each subscription. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/profiles/{user_id}/lists", user_id=user_id), + body=await async_maybe_transform({"lists": lists}, list_subscribe_params.ListSubscribeParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ListSubscribeResponse, + ) + + +class ListsResourceWithRawResponse: + def __init__(self, lists: ListsResource) -> None: + self._lists = lists + + self.retrieve = to_raw_response_wrapper( + lists.retrieve, + ) + self.delete = to_raw_response_wrapper( + lists.delete, + ) + self.subscribe = to_raw_response_wrapper( + lists.subscribe, + ) + + +class AsyncListsResourceWithRawResponse: + def __init__(self, lists: AsyncListsResource) -> None: + self._lists = lists + + self.retrieve = async_to_raw_response_wrapper( + lists.retrieve, + ) + self.delete = async_to_raw_response_wrapper( + lists.delete, + ) + self.subscribe = async_to_raw_response_wrapper( + lists.subscribe, + ) + + +class ListsResourceWithStreamingResponse: + def __init__(self, lists: ListsResource) -> None: + self._lists = lists + + self.retrieve = to_streamed_response_wrapper( + lists.retrieve, + ) + self.delete = to_streamed_response_wrapper( + lists.delete, + ) + self.subscribe = to_streamed_response_wrapper( + lists.subscribe, + ) + + +class AsyncListsResourceWithStreamingResponse: + def __init__(self, lists: AsyncListsResource) -> None: + self._lists = lists + + self.retrieve = async_to_streamed_response_wrapper( + lists.retrieve, + ) + self.delete = async_to_streamed_response_wrapper( + lists.delete, + ) + self.subscribe = async_to_streamed_response_wrapper( + lists.subscribe, + ) diff --git a/src/courier/resources/profiles/profiles.py b/src/courier/resources/profiles/profiles.py new file mode 100644 index 00000000..afd7d636 --- /dev/null +++ b/src/courier/resources/profiles/profiles.py @@ -0,0 +1,595 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Iterable + +import httpx + +from .lists import ( + ListsResource, + AsyncListsResource, + ListsResourceWithRawResponse, + AsyncListsResourceWithRawResponse, + ListsResourceWithStreamingResponse, + AsyncListsResourceWithStreamingResponse, +) +from ...types import profile_create_params, profile_update_params, profile_replace_params +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.profile_create_response import ProfileCreateResponse +from ...types.profile_replace_response import ProfileReplaceResponse +from ...types.profile_retrieve_response import ProfileRetrieveResponse + +__all__ = ["ProfilesResource", "AsyncProfilesResource"] + + +class ProfilesResource(SyncAPIResource): + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + + @cached_property + def lists(self) -> ListsResource: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + return ListsResource(self._client) + + @cached_property + def with_raw_response(self) -> ProfilesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return ProfilesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ProfilesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return ProfilesResourceWithStreamingResponse(self) + + def create( + self, + user_id: str, + *, + profile: Dict[str, object], + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProfileCreateResponse: + """ + Merges the supplied values into a user's profile, creating it if absent and + leaving any key you omit untouched. Prefer this for everyday writes. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/profiles/{user_id}", user_id=user_id), + body=maybe_transform({"profile": profile}, profile_create_params.ProfileCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ProfileCreateResponse, + ) + + def retrieve( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProfileRetrieveResponse: + """ + Returns a user's stored profile and preferences, including the email address, + phone number, and push tokens Courier can reach them on. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._get( + path_template("/profiles/{user_id}", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ProfileRetrieveResponse, + ) + + def update( + self, + user_id: str, + *, + patch: Iterable[profile_update_params.Patch], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Applies a JSON Patch to a user profile, adding, removing, or replacing + individual fields without sending the whole object. + + Args: + patch: List of patch operations to apply to the profile. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._patch( + path_template("/profiles/{user_id}", user_id=user_id), + body=maybe_transform({"patch": patch}, profile_update_params.ProfileUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def delete( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a user's profile and stored contact details. + + List subscriptions and + preferences are separate resources, so remove those too if required. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/profiles/{user_id}", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def replace( + self, + user_id: str, + *, + profile: Dict[str, object], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProfileReplaceResponse: + """Overwrites a user profile in full, removing any key absent from the request + body. + + Use the patch endpoint when changing a single field. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._put( + path_template("/profiles/{user_id}", user_id=user_id), + body=maybe_transform({"profile": profile}, profile_replace_params.ProfileReplaceParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ProfileReplaceResponse, + ) + + +class AsyncProfilesResource(AsyncAPIResource): + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + + @cached_property + def lists(self) -> AsyncListsResource: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + return AsyncListsResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncProfilesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncProfilesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncProfilesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncProfilesResourceWithStreamingResponse(self) + + async def create( + self, + user_id: str, + *, + profile: Dict[str, object], + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProfileCreateResponse: + """ + Merges the supplied values into a user's profile, creating it if absent and + leaving any key you omit untouched. Prefer this for everyday writes. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/profiles/{user_id}", user_id=user_id), + body=await async_maybe_transform({"profile": profile}, profile_create_params.ProfileCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ProfileCreateResponse, + ) + + async def retrieve( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProfileRetrieveResponse: + """ + Returns a user's stored profile and preferences, including the email address, + phone number, and push tokens Courier can reach them on. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._get( + path_template("/profiles/{user_id}", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ProfileRetrieveResponse, + ) + + async def update( + self, + user_id: str, + *, + patch: Iterable[profile_update_params.Patch], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Applies a JSON Patch to a user profile, adding, removing, or replacing + individual fields without sending the whole object. + + Args: + patch: List of patch operations to apply to the profile. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._patch( + path_template("/profiles/{user_id}", user_id=user_id), + body=await async_maybe_transform({"patch": patch}, profile_update_params.ProfileUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def delete( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a user's profile and stored contact details. + + List subscriptions and + preferences are separate resources, so remove those too if required. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/profiles/{user_id}", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def replace( + self, + user_id: str, + *, + profile: Dict[str, object], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProfileReplaceResponse: + """Overwrites a user profile in full, removing any key absent from the request + body. + + Use the patch endpoint when changing a single field. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._put( + path_template("/profiles/{user_id}", user_id=user_id), + body=await async_maybe_transform({"profile": profile}, profile_replace_params.ProfileReplaceParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ProfileReplaceResponse, + ) + + +class ProfilesResourceWithRawResponse: + def __init__(self, profiles: ProfilesResource) -> None: + self._profiles = profiles + + self.create = to_raw_response_wrapper( + profiles.create, + ) + self.retrieve = to_raw_response_wrapper( + profiles.retrieve, + ) + self.update = to_raw_response_wrapper( + profiles.update, + ) + self.delete = to_raw_response_wrapper( + profiles.delete, + ) + self.replace = to_raw_response_wrapper( + profiles.replace, + ) + + @cached_property + def lists(self) -> ListsResourceWithRawResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + return ListsResourceWithRawResponse(self._profiles.lists) + + +class AsyncProfilesResourceWithRawResponse: + def __init__(self, profiles: AsyncProfilesResource) -> None: + self._profiles = profiles + + self.create = async_to_raw_response_wrapper( + profiles.create, + ) + self.retrieve = async_to_raw_response_wrapper( + profiles.retrieve, + ) + self.update = async_to_raw_response_wrapper( + profiles.update, + ) + self.delete = async_to_raw_response_wrapper( + profiles.delete, + ) + self.replace = async_to_raw_response_wrapper( + profiles.replace, + ) + + @cached_property + def lists(self) -> AsyncListsResourceWithRawResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + return AsyncListsResourceWithRawResponse(self._profiles.lists) + + +class ProfilesResourceWithStreamingResponse: + def __init__(self, profiles: ProfilesResource) -> None: + self._profiles = profiles + + self.create = to_streamed_response_wrapper( + profiles.create, + ) + self.retrieve = to_streamed_response_wrapper( + profiles.retrieve, + ) + self.update = to_streamed_response_wrapper( + profiles.update, + ) + self.delete = to_streamed_response_wrapper( + profiles.delete, + ) + self.replace = to_streamed_response_wrapper( + profiles.replace, + ) + + @cached_property + def lists(self) -> ListsResourceWithStreamingResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + return ListsResourceWithStreamingResponse(self._profiles.lists) + + +class AsyncProfilesResourceWithStreamingResponse: + def __init__(self, profiles: AsyncProfilesResource) -> None: + self._profiles = profiles + + self.create = async_to_streamed_response_wrapper( + profiles.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + profiles.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + profiles.update, + ) + self.delete = async_to_streamed_response_wrapper( + profiles.delete, + ) + self.replace = async_to_streamed_response_wrapper( + profiles.replace, + ) + + @cached_property + def lists(self) -> AsyncListsResourceWithStreamingResponse: + """ + Store the contact information Courier delivers to for each user — email, phone number, push tokens, and any custom data you send to. + """ + return AsyncListsResourceWithStreamingResponse(self._profiles.lists) diff --git a/src/courier/resources/providers/__init__.py b/src/courier/resources/providers/__init__.py new file mode 100644 index 00000000..d351e5e8 --- /dev/null +++ b/src/courier/resources/providers/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .catalog import ( + CatalogResource, + AsyncCatalogResource, + CatalogResourceWithRawResponse, + AsyncCatalogResourceWithRawResponse, + CatalogResourceWithStreamingResponse, + AsyncCatalogResourceWithStreamingResponse, +) +from .providers import ( + ProvidersResource, + AsyncProvidersResource, + ProvidersResourceWithRawResponse, + AsyncProvidersResourceWithRawResponse, + ProvidersResourceWithStreamingResponse, + AsyncProvidersResourceWithStreamingResponse, +) + +__all__ = [ + "CatalogResource", + "AsyncCatalogResource", + "CatalogResourceWithRawResponse", + "AsyncCatalogResourceWithRawResponse", + "CatalogResourceWithStreamingResponse", + "AsyncCatalogResourceWithStreamingResponse", + "ProvidersResource", + "AsyncProvidersResource", + "ProvidersResourceWithRawResponse", + "AsyncProvidersResourceWithRawResponse", + "ProvidersResourceWithStreamingResponse", + "AsyncProvidersResourceWithStreamingResponse", +] diff --git a/src/courier/resources/providers/catalog.py b/src/courier/resources/providers/catalog.py new file mode 100644 index 00000000..57daa70d --- /dev/null +++ b/src/courier/resources/providers/catalog.py @@ -0,0 +1,211 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from ..._utils import maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.providers import catalog_list_params +from ...types.providers.catalog_list_response import CatalogListResponse + +__all__ = ["CatalogResource", "AsyncCatalogResource"] + + +class CatalogResource(SyncAPIResource): + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + + @cached_property + def with_raw_response(self) -> CatalogResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return CatalogResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> CatalogResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return CatalogResourceWithStreamingResponse(self) + + def list( + self, + *, + channel: str | Omit = omit, + keys: str | Omit = omit, + name: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CatalogListResponse: + """ + Returns the provider types Courier supports, each with a display name, + description, and the configuration fields it requires. + + Args: + channel: Exact match (case-insensitive) against the provider channel taxonomy (e.g. + `email`, `sms`, `push`). + + keys: Comma-separated provider keys to filter by (e.g. `sendgrid,twilio`). + + name: Case-insensitive substring match against the provider display name. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/providers/catalog", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "channel": channel, + "keys": keys, + "name": name, + }, + catalog_list_params.CatalogListParams, + ), + ), + cast_to=CatalogListResponse, + ) + + +class AsyncCatalogResource(AsyncAPIResource): + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + + @cached_property + def with_raw_response(self) -> AsyncCatalogResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncCatalogResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncCatalogResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncCatalogResourceWithStreamingResponse(self) + + async def list( + self, + *, + channel: str | Omit = omit, + keys: str | Omit = omit, + name: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> CatalogListResponse: + """ + Returns the provider types Courier supports, each with a display name, + description, and the configuration fields it requires. + + Args: + channel: Exact match (case-insensitive) against the provider channel taxonomy (e.g. + `email`, `sms`, `push`). + + keys: Comma-separated provider keys to filter by (e.g. `sendgrid,twilio`). + + name: Case-insensitive substring match against the provider display name. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/providers/catalog", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "channel": channel, + "keys": keys, + "name": name, + }, + catalog_list_params.CatalogListParams, + ), + ), + cast_to=CatalogListResponse, + ) + + +class CatalogResourceWithRawResponse: + def __init__(self, catalog: CatalogResource) -> None: + self._catalog = catalog + + self.list = to_raw_response_wrapper( + catalog.list, + ) + + +class AsyncCatalogResourceWithRawResponse: + def __init__(self, catalog: AsyncCatalogResource) -> None: + self._catalog = catalog + + self.list = async_to_raw_response_wrapper( + catalog.list, + ) + + +class CatalogResourceWithStreamingResponse: + def __init__(self, catalog: CatalogResource) -> None: + self._catalog = catalog + + self.list = to_streamed_response_wrapper( + catalog.list, + ) + + +class AsyncCatalogResourceWithStreamingResponse: + def __init__(self, catalog: AsyncCatalogResource) -> None: + self._catalog = catalog + + self.list = async_to_streamed_response_wrapper( + catalog.list, + ) diff --git a/src/courier/resources/providers/providers.py b/src/courier/resources/providers/providers.py new file mode 100644 index 00000000..dadeb0df --- /dev/null +++ b/src/courier/resources/providers/providers.py @@ -0,0 +1,670 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict + +import httpx + +from ...types import provider_list_params, provider_create_params, provider_update_params +from .catalog import ( + CatalogResource, + AsyncCatalogResource, + CatalogResourceWithRawResponse, + AsyncCatalogResourceWithRawResponse, + CatalogResourceWithStreamingResponse, + AsyncCatalogResourceWithStreamingResponse, +) +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.provider import Provider +from ...types.provider_list_response import ProviderListResponse + +__all__ = ["ProvidersResource", "AsyncProvidersResource"] + + +class ProvidersResource(SyncAPIResource): + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + + @cached_property + def catalog(self) -> CatalogResource: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + return CatalogResource(self._client) + + @cached_property + def with_raw_response(self) -> ProvidersResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return ProvidersResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ProvidersResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return ProvidersResourceWithStreamingResponse(self) + + def create( + self, + *, + provider: str, + alias: str | Omit = omit, + settings: Dict[str, object] | Omit = omit, + title: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Provider: + """ + Configures a provider integration from a Courier provider key and its settings. + Check the catalog endpoint for the schema each provider expects. + + Args: + provider: The provider key identifying the type (e.g. "sendgrid", "twilio"). Must be a + known Courier provider — see the catalog endpoint for valid keys. + + alias: Optional alias for this configuration. + + settings: Provider-specific settings (snake_case keys). Defaults to an empty object when + omitted. Use the catalog endpoint to discover required fields for a given + provider — omitting a required field returns a 400 validation error. + + title: Optional display title. Omit to use "Default Configuration". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/providers", + body=maybe_transform( + { + "provider": provider, + "alias": alias, + "settings": settings, + "title": title, + }, + provider_create_params.ProviderCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Provider, + ) + + def retrieve( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Provider: + """ + Returns one configured provider by id, including its channel, provider key, + alias, title, and current settings. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + path_template("/providers/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Provider, + ) + + def update( + self, + id: str, + *, + provider: str, + alias: str | Omit = omit, + settings: Dict[str, object] | Omit = omit, + title: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Provider: + """ + Replaces a provider's configuration in full, clearing any field you omit rather + than merging it. Send the complete settings object. + + Args: + provider: The provider key identifying the type. Required on every request because it + selects the provider-specific settings schema for validation. + + alias: Updated alias. Omit to clear. + + settings: Provider-specific settings (snake_case keys). Replaces the full settings object + — omitted settings fields are removed. Use the catalog endpoint to check + required fields. + + title: Updated display title. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._put( + path_template("/providers/{id}", id=id), + body=maybe_transform( + { + "provider": provider, + "alias": alias, + "settings": settings, + "title": title, + }, + provider_update_params.ProviderUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Provider, + ) + + def list( + self, + *, + cursor: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProviderListResponse: + """ + Lists the provider integrations configured in the workspace, one entry per + channel and provider key with its alias and settings. + + Args: + cursor: Opaque cursor for fetching the next page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/providers", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"cursor": cursor}, provider_list_params.ProviderListParams), + ), + cast_to=ProviderListResponse, + ) + + def delete( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Deletes a provider configuration, which fails while routing strategies or + templates still reference it. Update those references first. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/providers/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncProvidersResource(AsyncAPIResource): + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + + @cached_property + def catalog(self) -> AsyncCatalogResource: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + return AsyncCatalogResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncProvidersResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncProvidersResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncProvidersResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncProvidersResourceWithStreamingResponse(self) + + async def create( + self, + *, + provider: str, + alias: str | Omit = omit, + settings: Dict[str, object] | Omit = omit, + title: str | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Provider: + """ + Configures a provider integration from a Courier provider key and its settings. + Check the catalog endpoint for the schema each provider expects. + + Args: + provider: The provider key identifying the type (e.g. "sendgrid", "twilio"). Must be a + known Courier provider — see the catalog endpoint for valid keys. + + alias: Optional alias for this configuration. + + settings: Provider-specific settings (snake_case keys). Defaults to an empty object when + omitted. Use the catalog endpoint to discover required fields for a given + provider — omitting a required field returns a 400 validation error. + + title: Optional display title. Omit to use "Default Configuration". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/providers", + body=await async_maybe_transform( + { + "provider": provider, + "alias": alias, + "settings": settings, + "title": title, + }, + provider_create_params.ProviderCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Provider, + ) + + async def retrieve( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Provider: + """ + Returns one configured provider by id, including its channel, provider key, + alias, title, and current settings. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + path_template("/providers/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Provider, + ) + + async def update( + self, + id: str, + *, + provider: str, + alias: str | Omit = omit, + settings: Dict[str, object] | Omit = omit, + title: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Provider: + """ + Replaces a provider's configuration in full, clearing any field you omit rather + than merging it. Send the complete settings object. + + Args: + provider: The provider key identifying the type. Required on every request because it + selects the provider-specific settings schema for validation. + + alias: Updated alias. Omit to clear. + + settings: Provider-specific settings (snake_case keys). Replaces the full settings object + — omitted settings fields are removed. Use the catalog endpoint to check + required fields. + + title: Updated display title. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._put( + path_template("/providers/{id}", id=id), + body=await async_maybe_transform( + { + "provider": provider, + "alias": alias, + "settings": settings, + "title": title, + }, + provider_update_params.ProviderUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Provider, + ) + + async def list( + self, + *, + cursor: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> ProviderListResponse: + """ + Lists the provider integrations configured in the workspace, one entry per + channel and provider key with its alias and settings. + + Args: + cursor: Opaque cursor for fetching the next page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/providers", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"cursor": cursor}, provider_list_params.ProviderListParams), + ), + cast_to=ProviderListResponse, + ) + + async def delete( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Deletes a provider configuration, which fails while routing strategies or + templates still reference it. Update those references first. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/providers/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class ProvidersResourceWithRawResponse: + def __init__(self, providers: ProvidersResource) -> None: + self._providers = providers + + self.create = to_raw_response_wrapper( + providers.create, + ) + self.retrieve = to_raw_response_wrapper( + providers.retrieve, + ) + self.update = to_raw_response_wrapper( + providers.update, + ) + self.list = to_raw_response_wrapper( + providers.list, + ) + self.delete = to_raw_response_wrapper( + providers.delete, + ) + + @cached_property + def catalog(self) -> CatalogResourceWithRawResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + return CatalogResourceWithRawResponse(self._providers.catalog) + + +class AsyncProvidersResourceWithRawResponse: + def __init__(self, providers: AsyncProvidersResource) -> None: + self._providers = providers + + self.create = async_to_raw_response_wrapper( + providers.create, + ) + self.retrieve = async_to_raw_response_wrapper( + providers.retrieve, + ) + self.update = async_to_raw_response_wrapper( + providers.update, + ) + self.list = async_to_raw_response_wrapper( + providers.list, + ) + self.delete = async_to_raw_response_wrapper( + providers.delete, + ) + + @cached_property + def catalog(self) -> AsyncCatalogResourceWithRawResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + return AsyncCatalogResourceWithRawResponse(self._providers.catalog) + + +class ProvidersResourceWithStreamingResponse: + def __init__(self, providers: ProvidersResource) -> None: + self._providers = providers + + self.create = to_streamed_response_wrapper( + providers.create, + ) + self.retrieve = to_streamed_response_wrapper( + providers.retrieve, + ) + self.update = to_streamed_response_wrapper( + providers.update, + ) + self.list = to_streamed_response_wrapper( + providers.list, + ) + self.delete = to_streamed_response_wrapper( + providers.delete, + ) + + @cached_property + def catalog(self) -> CatalogResourceWithStreamingResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + return CatalogResourceWithStreamingResponse(self._providers.catalog) + + +class AsyncProvidersResourceWithStreamingResponse: + def __init__(self, providers: AsyncProvidersResource) -> None: + self._providers = providers + + self.create = async_to_streamed_response_wrapper( + providers.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + providers.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + providers.update, + ) + self.list = async_to_streamed_response_wrapper( + providers.list, + ) + self.delete = async_to_streamed_response_wrapper( + providers.delete, + ) + + @cached_property + def catalog(self) -> AsyncCatalogResourceWithStreamingResponse: + """ + Configure the channel providers Courier delivers through, and browse the provider types it supports. + """ + return AsyncCatalogResourceWithStreamingResponse(self._providers.catalog) diff --git a/src/courier/resources/requests.py b/src/courier/resources/requests.py new file mode 100644 index 00000000..3dfd380a --- /dev/null +++ b/src/courier/resources/requests.py @@ -0,0 +1,177 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from .._types import Body, Query, Headers, NoneType, NotGiven, not_given +from .._utils import path_template +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options + +__all__ = ["RequestsResource", "AsyncRequestsResource"] + + +class RequestsResource(SyncAPIResource): + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + + @cached_property + def with_raw_response(self) -> RequestsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return RequestsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> RequestsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return RequestsResourceWithStreamingResponse(self) + + def archive( + self, + request_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives a send request by its request id. + + Use it to remove test sends or + superseded requests from the message list without deleting them. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not request_id: + raise ValueError(f"Expected a non-empty value for `request_id` but received {request_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/requests/{request_id}/archive", request_id=request_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncRequestsResource(AsyncAPIResource): + """ + Look up the messages Courier has accepted, inspect their delivery history and rendered output, and cancel, resend, or archive them. + """ + + @cached_property + def with_raw_response(self) -> AsyncRequestsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncRequestsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncRequestsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncRequestsResourceWithStreamingResponse(self) + + async def archive( + self, + request_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archives a send request by its request id. + + Use it to remove test sends or + superseded requests from the message list without deleting them. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not request_id: + raise ValueError(f"Expected a non-empty value for `request_id` but received {request_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/requests/{request_id}/archive", request_id=request_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class RequestsResourceWithRawResponse: + def __init__(self, requests: RequestsResource) -> None: + self._requests = requests + + self.archive = to_raw_response_wrapper( + requests.archive, + ) + + +class AsyncRequestsResourceWithRawResponse: + def __init__(self, requests: AsyncRequestsResource) -> None: + self._requests = requests + + self.archive = async_to_raw_response_wrapper( + requests.archive, + ) + + +class RequestsResourceWithStreamingResponse: + def __init__(self, requests: RequestsResource) -> None: + self._requests = requests + + self.archive = to_streamed_response_wrapper( + requests.archive, + ) + + +class AsyncRequestsResourceWithStreamingResponse: + def __init__(self, requests: AsyncRequestsResource) -> None: + self._requests = requests + + self.archive = async_to_streamed_response_wrapper( + requests.archive, + ) diff --git a/src/courier/resources/routing_strategies.py b/src/courier/resources/routing_strategies.py new file mode 100644 index 00000000..48aaf066 --- /dev/null +++ b/src/courier/resources/routing_strategies.py @@ -0,0 +1,791 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +import httpx + +from ..types import ( + routing_strategy_list_params, + routing_strategy_create_params, + routing_strategy_replace_params, + routing_strategy_list_notifications_params, +) +from .._types import Body, Omit, Query, Headers, NoneType, NotGiven, SequenceNotStr, omit, not_given +from .._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.routing_strategy_get_response import RoutingStrategyGetResponse +from ..types.shared_params.message_routing import MessageRouting +from ..types.routing_strategy_list_response import RoutingStrategyListResponse +from ..types.shared_params.message_channels import MessageChannels +from ..types.shared_params.message_providers import MessageProviders +from ..types.associated_notification_list_response import AssociatedNotificationListResponse + +__all__ = ["RoutingStrategiesResource", "AsyncRoutingStrategiesResource"] + + +class RoutingStrategiesResource(SyncAPIResource): + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + + @cached_property + def with_raw_response(self) -> RoutingStrategiesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return RoutingStrategiesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> RoutingStrategiesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return RoutingStrategiesResourceWithStreamingResponse(self) + + def create( + self, + *, + name: str, + routing: MessageRouting, + channels: Optional[MessageChannels] | Omit = omit, + description: Optional[str] | Omit = omit, + providers: Optional[MessageProviders] | Omit = omit, + tags: Optional[SequenceNotStr[str]] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyGetResponse: + """Create a routing strategy. + + Requires a name and routing configuration at minimum. + Channels and providers default to empty if omitted. + + Args: + name: Human-readable name for the routing strategy. + + routing: Routing tree defining channel selection method and order. + + channels: Per-channel delivery configuration. Defaults to empty if omitted. + + description: Optional description of the routing strategy. + + providers: Per-provider delivery configuration. Defaults to empty if omitted. + + tags: Optional tags for categorization. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/routing-strategies", + body=maybe_transform( + { + "name": name, + "routing": routing, + "channels": channels, + "description": description, + "providers": providers, + "tags": tags, + }, + routing_strategy_create_params.RoutingStrategyCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RoutingStrategyGetResponse, + ) + + def retrieve( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyGetResponse: + """ + Returns one routing strategy by id with its name, tags, channels, and the + routing rules that decide provider order and fallback. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + path_template("/routing-strategies/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RoutingStrategyGetResponse, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyListResponse: + """List routing strategies in your workspace. + + Returns metadata only (no + routing/channels/providers content). Use GET /routing-strategies/{id} for full + details. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of results per page. Default 20, max 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/routing-strategies", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + routing_strategy_list_params.RoutingStrategyListParams, + ), + ), + cast_to=RoutingStrategyListResponse, + ) + + def archive( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archive a routing strategy. + + The strategy must not have associated notification + templates. Unlink all templates before archiving. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/routing-strategies/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def list_notifications( + self, + id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AssociatedNotificationListResponse: + """Returns the notification templates using a routing strategy, with paging. + + Check + this before changing a strategy that templates depend on. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of results per page. Default 20, max 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._get( + path_template("/routing-strategies/{id}/notifications", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + routing_strategy_list_notifications_params.RoutingStrategyListNotificationsParams, + ), + ), + cast_to=AssociatedNotificationListResponse, + ) + + def replace( + self, + id: str, + *, + name: str, + routing: MessageRouting, + channels: Optional[MessageChannels] | Omit = omit, + description: Optional[str] | Omit = omit, + providers: Optional[MessageProviders] | Omit = omit, + tags: Optional[SequenceNotStr[str]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyGetResponse: + """Replace a routing strategy. + + Full document replacement; the caller must send the + complete desired state. Missing optional fields are cleared. + + Args: + name: Human-readable name for the routing strategy. + + routing: Routing tree defining channel selection method and order. + + channels: Per-channel delivery configuration. Omit to clear. + + description: Optional description. Omit or null to clear. + + providers: Per-provider delivery configuration. Omit to clear. + + tags: Optional tags. Omit or null to clear. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return self._put( + path_template("/routing-strategies/{id}", id=id), + body=maybe_transform( + { + "name": name, + "routing": routing, + "channels": channels, + "description": description, + "providers": providers, + "tags": tags, + }, + routing_strategy_replace_params.RoutingStrategyReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RoutingStrategyGetResponse, + ) + + +class AsyncRoutingStrategiesResource(AsyncAPIResource): + """ + Define reusable channel routing and failover strategies, and see which templates use them. + """ + + @cached_property + def with_raw_response(self) -> AsyncRoutingStrategiesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncRoutingStrategiesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncRoutingStrategiesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncRoutingStrategiesResourceWithStreamingResponse(self) + + async def create( + self, + *, + name: str, + routing: MessageRouting, + channels: Optional[MessageChannels] | Omit = omit, + description: Optional[str] | Omit = omit, + providers: Optional[MessageProviders] | Omit = omit, + tags: Optional[SequenceNotStr[str]] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyGetResponse: + """Create a routing strategy. + + Requires a name and routing configuration at minimum. + Channels and providers default to empty if omitted. + + Args: + name: Human-readable name for the routing strategy. + + routing: Routing tree defining channel selection method and order. + + channels: Per-channel delivery configuration. Defaults to empty if omitted. + + description: Optional description of the routing strategy. + + providers: Per-provider delivery configuration. Defaults to empty if omitted. + + tags: Optional tags for categorization. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/routing-strategies", + body=await async_maybe_transform( + { + "name": name, + "routing": routing, + "channels": channels, + "description": description, + "providers": providers, + "tags": tags, + }, + routing_strategy_create_params.RoutingStrategyCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RoutingStrategyGetResponse, + ) + + async def retrieve( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyGetResponse: + """ + Returns one routing strategy by id with its name, tags, channels, and the + routing rules that decide provider order and fallback. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + path_template("/routing-strategies/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RoutingStrategyGetResponse, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyListResponse: + """List routing strategies in your workspace. + + Returns metadata only (no + routing/channels/providers content). Use GET /routing-strategies/{id} for full + details. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of results per page. Default 20, max 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/routing-strategies", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + routing_strategy_list_params.RoutingStrategyListParams, + ), + ), + cast_to=RoutingStrategyListResponse, + ) + + async def archive( + self, + id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archive a routing strategy. + + The strategy must not have associated notification + templates. Unlink all templates before archiving. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/routing-strategies/{id}", id=id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def list_notifications( + self, + id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: int | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> AssociatedNotificationListResponse: + """Returns the notification templates using a routing strategy, with paging. + + Check + this before changing a strategy that templates depend on. + + Args: + cursor: Opaque pagination cursor from a previous response. Omit for the first page. + + limit: Maximum number of results per page. Default 20, max 100. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._get( + path_template("/routing-strategies/{id}/notifications", id=id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + routing_strategy_list_notifications_params.RoutingStrategyListNotificationsParams, + ), + ), + cast_to=AssociatedNotificationListResponse, + ) + + async def replace( + self, + id: str, + *, + name: str, + routing: MessageRouting, + channels: Optional[MessageChannels] | Omit = omit, + description: Optional[str] | Omit = omit, + providers: Optional[MessageProviders] | Omit = omit, + tags: Optional[SequenceNotStr[str]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> RoutingStrategyGetResponse: + """Replace a routing strategy. + + Full document replacement; the caller must send the + complete desired state. Missing optional fields are cleared. + + Args: + name: Human-readable name for the routing strategy. + + routing: Routing tree defining channel selection method and order. + + channels: Per-channel delivery configuration. Omit to clear. + + description: Optional description. Omit or null to clear. + + providers: Per-provider delivery configuration. Omit to clear. + + tags: Optional tags. Omit or null to clear. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not id: + raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") + return await self._put( + path_template("/routing-strategies/{id}", id=id), + body=await async_maybe_transform( + { + "name": name, + "routing": routing, + "channels": channels, + "description": description, + "providers": providers, + "tags": tags, + }, + routing_strategy_replace_params.RoutingStrategyReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RoutingStrategyGetResponse, + ) + + +class RoutingStrategiesResourceWithRawResponse: + def __init__(self, routing_strategies: RoutingStrategiesResource) -> None: + self._routing_strategies = routing_strategies + + self.create = to_raw_response_wrapper( + routing_strategies.create, + ) + self.retrieve = to_raw_response_wrapper( + routing_strategies.retrieve, + ) + self.list = to_raw_response_wrapper( + routing_strategies.list, + ) + self.archive = to_raw_response_wrapper( + routing_strategies.archive, + ) + self.list_notifications = to_raw_response_wrapper( + routing_strategies.list_notifications, + ) + self.replace = to_raw_response_wrapper( + routing_strategies.replace, + ) + + +class AsyncRoutingStrategiesResourceWithRawResponse: + def __init__(self, routing_strategies: AsyncRoutingStrategiesResource) -> None: + self._routing_strategies = routing_strategies + + self.create = async_to_raw_response_wrapper( + routing_strategies.create, + ) + self.retrieve = async_to_raw_response_wrapper( + routing_strategies.retrieve, + ) + self.list = async_to_raw_response_wrapper( + routing_strategies.list, + ) + self.archive = async_to_raw_response_wrapper( + routing_strategies.archive, + ) + self.list_notifications = async_to_raw_response_wrapper( + routing_strategies.list_notifications, + ) + self.replace = async_to_raw_response_wrapper( + routing_strategies.replace, + ) + + +class RoutingStrategiesResourceWithStreamingResponse: + def __init__(self, routing_strategies: RoutingStrategiesResource) -> None: + self._routing_strategies = routing_strategies + + self.create = to_streamed_response_wrapper( + routing_strategies.create, + ) + self.retrieve = to_streamed_response_wrapper( + routing_strategies.retrieve, + ) + self.list = to_streamed_response_wrapper( + routing_strategies.list, + ) + self.archive = to_streamed_response_wrapper( + routing_strategies.archive, + ) + self.list_notifications = to_streamed_response_wrapper( + routing_strategies.list_notifications, + ) + self.replace = to_streamed_response_wrapper( + routing_strategies.replace, + ) + + +class AsyncRoutingStrategiesResourceWithStreamingResponse: + def __init__(self, routing_strategies: AsyncRoutingStrategiesResource) -> None: + self._routing_strategies = routing_strategies + + self.create = async_to_streamed_response_wrapper( + routing_strategies.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + routing_strategies.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + routing_strategies.list, + ) + self.archive = async_to_streamed_response_wrapper( + routing_strategies.archive, + ) + self.list_notifications = async_to_streamed_response_wrapper( + routing_strategies.list_notifications, + ) + self.replace = async_to_streamed_response_wrapper( + routing_strategies.replace, + ) diff --git a/src/courier/resources/send.py b/src/courier/resources/send.py new file mode 100644 index 00000000..1c25a491 --- /dev/null +++ b/src/courier/resources/send.py @@ -0,0 +1,203 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ..types import send_message_params +from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given +from .._utils import maybe_transform, strip_not_given, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options +from ..types.send_message_response import SendMessageResponse + +__all__ = ["SendResource", "AsyncSendResource"] + + +class SendResource(SyncAPIResource): + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + + @cached_property + def with_raw_response(self) -> SendResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return SendResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> SendResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return SendResourceWithStreamingResponse(self) + + def message( + self, + *, + message: send_message_params.Message, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> SendMessageResponse: + """Sends a message to one or more recipients and returns a requestId. + + Courier + routes it to email, SMS, push, chat, or in-app based on your rules. + + Args: + message: The message property has the following primary top-level properties. They define + the destination and content of the message. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/send", + body=maybe_transform({"message": message}, send_message_params.SendMessageParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=SendMessageResponse, + ) + + +class AsyncSendResource(AsyncAPIResource): + """ + Send a message to one or more recipients — users, lists, audiences, or tenants — across every channel you have configured. + """ + + @cached_property + def with_raw_response(self) -> AsyncSendResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncSendResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncSendResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncSendResourceWithStreamingResponse(self) + + async def message( + self, + *, + message: send_message_params.Message, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> SendMessageResponse: + """Sends a message to one or more recipients and returns a requestId. + + Courier + routes it to email, SMS, push, chat, or in-app based on your rules. + + Args: + message: The message property has the following primary top-level properties. They define + the destination and content of the message. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/send", + body=await async_maybe_transform({"message": message}, send_message_params.SendMessageParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=SendMessageResponse, + ) + + +class SendResourceWithRawResponse: + def __init__(self, send: SendResource) -> None: + self._send = send + + self.message = to_raw_response_wrapper( + send.message, + ) + + +class AsyncSendResourceWithRawResponse: + def __init__(self, send: AsyncSendResource) -> None: + self._send = send + + self.message = async_to_raw_response_wrapper( + send.message, + ) + + +class SendResourceWithStreamingResponse: + def __init__(self, send: SendResource) -> None: + self._send = send + + self.message = to_streamed_response_wrapper( + send.message, + ) + + +class AsyncSendResourceWithStreamingResponse: + def __init__(self, send: AsyncSendResource) -> None: + self._send = send + + self.message = async_to_streamed_response_wrapper( + send.message, + ) diff --git a/src/courier/resources/tenants/__init__.py b/src/courier/resources/tenants/__init__.py new file mode 100644 index 00000000..320a6a01 --- /dev/null +++ b/src/courier/resources/tenants/__init__.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .tenants import ( + TenantsResource, + AsyncTenantsResource, + TenantsResourceWithRawResponse, + AsyncTenantsResourceWithRawResponse, + TenantsResourceWithStreamingResponse, + AsyncTenantsResourceWithStreamingResponse, +) +from .templates import ( + TemplatesResource, + AsyncTemplatesResource, + TemplatesResourceWithRawResponse, + AsyncTemplatesResourceWithRawResponse, + TemplatesResourceWithStreamingResponse, + AsyncTemplatesResourceWithStreamingResponse, +) +from .preferences import ( + PreferencesResource, + AsyncPreferencesResource, + PreferencesResourceWithRawResponse, + AsyncPreferencesResourceWithRawResponse, + PreferencesResourceWithStreamingResponse, + AsyncPreferencesResourceWithStreamingResponse, +) + +__all__ = [ + "PreferencesResource", + "AsyncPreferencesResource", + "PreferencesResourceWithRawResponse", + "AsyncPreferencesResourceWithRawResponse", + "PreferencesResourceWithStreamingResponse", + "AsyncPreferencesResourceWithStreamingResponse", + "TemplatesResource", + "AsyncTemplatesResource", + "TemplatesResourceWithRawResponse", + "AsyncTemplatesResourceWithRawResponse", + "TemplatesResourceWithStreamingResponse", + "AsyncTemplatesResourceWithStreamingResponse", + "TenantsResource", + "AsyncTenantsResource", + "TenantsResourceWithRawResponse", + "AsyncTenantsResourceWithRawResponse", + "TenantsResourceWithStreamingResponse", + "AsyncTenantsResourceWithStreamingResponse", +] diff --git a/src/courier/resources/tenants/preferences/__init__.py b/src/courier/resources/tenants/preferences/__init__.py new file mode 100644 index 00000000..09ca62e6 --- /dev/null +++ b/src/courier/resources/tenants/preferences/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .items import ( + ItemsResource, + AsyncItemsResource, + ItemsResourceWithRawResponse, + AsyncItemsResourceWithRawResponse, + ItemsResourceWithStreamingResponse, + AsyncItemsResourceWithStreamingResponse, +) +from .preferences import ( + PreferencesResource, + AsyncPreferencesResource, + PreferencesResourceWithRawResponse, + AsyncPreferencesResourceWithRawResponse, + PreferencesResourceWithStreamingResponse, + AsyncPreferencesResourceWithStreamingResponse, +) + +__all__ = [ + "ItemsResource", + "AsyncItemsResource", + "ItemsResourceWithRawResponse", + "AsyncItemsResourceWithRawResponse", + "ItemsResourceWithStreamingResponse", + "AsyncItemsResourceWithStreamingResponse", + "PreferencesResource", + "AsyncPreferencesResource", + "PreferencesResourceWithRawResponse", + "AsyncPreferencesResourceWithRawResponse", + "PreferencesResourceWithStreamingResponse", + "AsyncPreferencesResourceWithStreamingResponse", +] diff --git a/src/courier/resources/tenants/preferences/items.py b/src/courier/resources/tenants/preferences/items.py new file mode 100644 index 00000000..103d9af3 --- /dev/null +++ b/src/courier/resources/tenants/preferences/items.py @@ -0,0 +1,316 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal + +import httpx + +from ...._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ...._utils import path_template, maybe_transform, async_maybe_transform +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...._base_client import make_request_options +from ....types.tenants.preferences import item_update_params +from ....types.shared.channel_classification import ChannelClassification + +__all__ = ["ItemsResource", "AsyncItemsResource"] + + +class ItemsResource(SyncAPIResource): + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + + @cached_property + def with_raw_response(self) -> ItemsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return ItemsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ItemsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return ItemsResourceWithStreamingResponse(self) + + def update( + self, + topic_id: str, + *, + tenant_id: str, + status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"], + custom_routing: Optional[List[ChannelClassification]] | Omit = omit, + has_custom_routing: Optional[bool] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Sets a tenant's default opt-in status for one subscription topic, which applies + to every member unless a user sets their own override. + + Args: + custom_routing: The default channels to send to this tenant when has_custom_routing is enabled + + has_custom_routing: Override channel routing with custom preferences. This will override any + template preferences that are set, but a user can still customize their + preferences + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template( + "/tenants/{tenant_id}/default_preferences/items/{topic_id}", tenant_id=tenant_id, topic_id=topic_id + ), + body=maybe_transform( + { + "status": status, + "custom_routing": custom_routing, + "has_custom_routing": has_custom_routing, + }, + item_update_params.ItemUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def delete( + self, + topic_id: str, + *, + tenant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Removes a tenant's default preference for one subscription topic, addressed by + tenant id and topic id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template( + "/tenants/{tenant_id}/default_preferences/items/{topic_id}", tenant_id=tenant_id, topic_id=topic_id + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncItemsResource(AsyncAPIResource): + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + + @cached_property + def with_raw_response(self) -> AsyncItemsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncItemsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncItemsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncItemsResourceWithStreamingResponse(self) + + async def update( + self, + topic_id: str, + *, + tenant_id: str, + status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"], + custom_routing: Optional[List[ChannelClassification]] | Omit = omit, + has_custom_routing: Optional[bool] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Sets a tenant's default opt-in status for one subscription topic, which applies + to every member unless a user sets their own override. + + Args: + custom_routing: The default channels to send to this tenant when has_custom_routing is enabled + + has_custom_routing: Override channel routing with custom preferences. This will override any + template preferences that are set, but a user can still customize their + preferences + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template( + "/tenants/{tenant_id}/default_preferences/items/{topic_id}", tenant_id=tenant_id, topic_id=topic_id + ), + body=await async_maybe_transform( + { + "status": status, + "custom_routing": custom_routing, + "has_custom_routing": has_custom_routing, + }, + item_update_params.ItemUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def delete( + self, + topic_id: str, + *, + tenant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Removes a tenant's default preference for one subscription topic, addressed by + tenant id and topic id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template( + "/tenants/{tenant_id}/default_preferences/items/{topic_id}", tenant_id=tenant_id, topic_id=topic_id + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class ItemsResourceWithRawResponse: + def __init__(self, items: ItemsResource) -> None: + self._items = items + + self.update = to_raw_response_wrapper( + items.update, + ) + self.delete = to_raw_response_wrapper( + items.delete, + ) + + +class AsyncItemsResourceWithRawResponse: + def __init__(self, items: AsyncItemsResource) -> None: + self._items = items + + self.update = async_to_raw_response_wrapper( + items.update, + ) + self.delete = async_to_raw_response_wrapper( + items.delete, + ) + + +class ItemsResourceWithStreamingResponse: + def __init__(self, items: ItemsResource) -> None: + self._items = items + + self.update = to_streamed_response_wrapper( + items.update, + ) + self.delete = to_streamed_response_wrapper( + items.delete, + ) + + +class AsyncItemsResourceWithStreamingResponse: + def __init__(self, items: AsyncItemsResource) -> None: + self._items = items + + self.update = async_to_streamed_response_wrapper( + items.update, + ) + self.delete = async_to_streamed_response_wrapper( + items.delete, + ) diff --git a/src/courier/resources/tenants/preferences/preferences.py b/src/courier/resources/tenants/preferences/preferences.py new file mode 100644 index 00000000..6b0408dc --- /dev/null +++ b/src/courier/resources/tenants/preferences/preferences.py @@ -0,0 +1,120 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .items import ( + ItemsResource, + AsyncItemsResource, + ItemsResourceWithRawResponse, + AsyncItemsResourceWithRawResponse, + ItemsResourceWithStreamingResponse, + AsyncItemsResourceWithStreamingResponse, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource + +__all__ = ["PreferencesResource", "AsyncPreferencesResource"] + + +class PreferencesResource(SyncAPIResource): + @cached_property + def items(self) -> ItemsResource: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + return ItemsResource(self._client) + + @cached_property + def with_raw_response(self) -> PreferencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return PreferencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> PreferencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return PreferencesResourceWithStreamingResponse(self) + + +class AsyncPreferencesResource(AsyncAPIResource): + @cached_property + def items(self) -> AsyncItemsResource: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + return AsyncItemsResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncPreferencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncPreferencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncPreferencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncPreferencesResourceWithStreamingResponse(self) + + +class PreferencesResourceWithRawResponse: + def __init__(self, preferences: PreferencesResource) -> None: + self._preferences = preferences + + @cached_property + def items(self) -> ItemsResourceWithRawResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + return ItemsResourceWithRawResponse(self._preferences.items) + + +class AsyncPreferencesResourceWithRawResponse: + def __init__(self, preferences: AsyncPreferencesResource) -> None: + self._preferences = preferences + + @cached_property + def items(self) -> AsyncItemsResourceWithRawResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + return AsyncItemsResourceWithRawResponse(self._preferences.items) + + +class PreferencesResourceWithStreamingResponse: + def __init__(self, preferences: PreferencesResource) -> None: + self._preferences = preferences + + @cached_property + def items(self) -> ItemsResourceWithStreamingResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + return ItemsResourceWithStreamingResponse(self._preferences.items) + + +class AsyncPreferencesResourceWithStreamingResponse: + def __init__(self, preferences: AsyncPreferencesResource) -> None: + self._preferences = preferences + + @cached_property + def items(self) -> AsyncItemsResourceWithStreamingResponse: + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + return AsyncItemsResourceWithStreamingResponse(self._preferences.items) diff --git a/src/courier/resources/tenants/templates/__init__.py b/src/courier/resources/tenants/templates/__init__.py new file mode 100644 index 00000000..fdb74957 --- /dev/null +++ b/src/courier/resources/tenants/templates/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .versions import ( + VersionsResource, + AsyncVersionsResource, + VersionsResourceWithRawResponse, + AsyncVersionsResourceWithRawResponse, + VersionsResourceWithStreamingResponse, + AsyncVersionsResourceWithStreamingResponse, +) +from .templates import ( + TemplatesResource, + AsyncTemplatesResource, + TemplatesResourceWithRawResponse, + AsyncTemplatesResourceWithRawResponse, + TemplatesResourceWithStreamingResponse, + AsyncTemplatesResourceWithStreamingResponse, +) + +__all__ = [ + "VersionsResource", + "AsyncVersionsResource", + "VersionsResourceWithRawResponse", + "AsyncVersionsResourceWithRawResponse", + "VersionsResourceWithStreamingResponse", + "AsyncVersionsResourceWithStreamingResponse", + "TemplatesResource", + "AsyncTemplatesResource", + "TemplatesResourceWithRawResponse", + "AsyncTemplatesResourceWithRawResponse", + "TemplatesResourceWithStreamingResponse", + "AsyncTemplatesResourceWithStreamingResponse", +] diff --git a/src/courier/resources/tenants/templates/templates.py b/src/courier/resources/tenants/templates/templates.py new file mode 100644 index 00000000..20015941 --- /dev/null +++ b/src/courier/resources/tenants/templates/templates.py @@ -0,0 +1,655 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +import httpx + +from .versions import ( + VersionsResource, + AsyncVersionsResource, + VersionsResourceWithRawResponse, + AsyncVersionsResourceWithRawResponse, + VersionsResourceWithStreamingResponse, + AsyncVersionsResourceWithStreamingResponse, +) +from ...._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ...._utils import path_template, maybe_transform, async_maybe_transform +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...._base_client import make_request_options +from ....types.tenants import template_list_params, template_publish_params, template_replace_params +from ....types.tenant_template_input_param import TenantTemplateInputParam +from ....types.put_tenant_template_response import PutTenantTemplateResponse +from ....types.tenants.template_list_response import TemplateListResponse +from ....types.base_template_tenant_association import BaseTemplateTenantAssociation +from ....types.post_tenant_template_publish_response import PostTenantTemplatePublishResponse + +__all__ = ["TemplatesResource", "AsyncTemplatesResource"] + + +class TemplatesResource(SyncAPIResource): + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + + @cached_property + def versions(self) -> VersionsResource: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return VersionsResource(self._client) + + @cached_property + def with_raw_response(self) -> TemplatesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TemplatesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TemplatesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TemplatesResourceWithStreamingResponse(self) + + def retrieve( + self, + template_id: str, + *, + tenant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BaseTemplateTenantAssociation: + """ + Returns a tenant's notification template with its content, version, and created, + updated, and published timestamps. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._get( + path_template("/tenants/{tenant_id}/templates/{template_id}", tenant_id=tenant_id, template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BaseTemplateTenantAssociation, + ) + + def list( + self, + tenant_id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TemplateListResponse: + """ + Lists a tenant's notification templates, each carrying its version and published + timestamp. Paged. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of templates to return (defaults to 20, maximum value of 100) + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return self._get( + path_template("/tenants/{tenant_id}/templates", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + template_list_params.TemplateListParams, + ), + ), + cast_to=TemplateListResponse, + ) + + def delete( + self, + template_id: str, + *, + tenant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a tenant's notification template by id. + + Sends for that tenant then use + the workspace template registered under the same id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/tenants/{tenant_id}/templates/{template_id}", tenant_id=tenant_id, template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def publish( + self, + template_id: str, + *, + tenant_id: str, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PostTenantTemplatePublishResponse: + """ + Publishes a version of a tenant's notification template, making it the content + that tenant's sends render from until you publish another. + + Args: + version: The version of the template to publish (e.g., "v1", "v2", "latest"). If not + provided, defaults to "latest". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._post( + path_template( + "/tenants/{tenant_id}/templates/{template_id}/publish", tenant_id=tenant_id, template_id=template_id + ), + body=maybe_transform({"version": version}, template_publish_params.TemplatePublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PostTenantTemplatePublishResponse, + ) + + def replace( + self, + template_id: str, + *, + tenant_id: str, + template: TenantTemplateInputParam, + published: bool | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PutTenantTemplateResponse: + """ + Creates or updates a notification template scoped to one tenant, letting a + tenant override the content the workspace template would send. + + Args: + template: Template configuration for creating or updating a tenant notification template + + published: Whether to publish the template immediately after saving. When true, the + template becomes the active/published version. When false (default), the + template is saved as a draft. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return self._put( + path_template("/tenants/{tenant_id}/templates/{template_id}", tenant_id=tenant_id, template_id=template_id), + body=maybe_transform( + { + "template": template, + "published": published, + }, + template_replace_params.TemplateReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PutTenantTemplateResponse, + ) + + +class AsyncTemplatesResource(AsyncAPIResource): + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + + @cached_property + def versions(self) -> AsyncVersionsResource: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return AsyncVersionsResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncTemplatesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTemplatesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTemplatesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTemplatesResourceWithStreamingResponse(self) + + async def retrieve( + self, + template_id: str, + *, + tenant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BaseTemplateTenantAssociation: + """ + Returns a tenant's notification template with its content, version, and created, + updated, and published timestamps. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._get( + path_template("/tenants/{tenant_id}/templates/{template_id}", tenant_id=tenant_id, template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BaseTemplateTenantAssociation, + ) + + async def list( + self, + tenant_id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TemplateListResponse: + """ + Lists a tenant's notification templates, each carrying its version and published + timestamp. Paged. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of templates to return (defaults to 20, maximum value of 100) + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return await self._get( + path_template("/tenants/{tenant_id}/templates", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + template_list_params.TemplateListParams, + ), + ), + cast_to=TemplateListResponse, + ) + + async def delete( + self, + template_id: str, + *, + tenant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a tenant's notification template by id. + + Sends for that tenant then use + the workspace template registered under the same id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/tenants/{tenant_id}/templates/{template_id}", tenant_id=tenant_id, template_id=template_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def publish( + self, + template_id: str, + *, + tenant_id: str, + version: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PostTenantTemplatePublishResponse: + """ + Publishes a version of a tenant's notification template, making it the content + that tenant's sends render from until you publish another. + + Args: + version: The version of the template to publish (e.g., "v1", "v2", "latest"). If not + provided, defaults to "latest". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._post( + path_template( + "/tenants/{tenant_id}/templates/{template_id}/publish", tenant_id=tenant_id, template_id=template_id + ), + body=await async_maybe_transform({"version": version}, template_publish_params.TemplatePublishParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PostTenantTemplatePublishResponse, + ) + + async def replace( + self, + template_id: str, + *, + tenant_id: str, + template: TenantTemplateInputParam, + published: bool | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PutTenantTemplateResponse: + """ + Creates or updates a notification template scoped to one tenant, letting a + tenant override the content the workspace template would send. + + Args: + template: Template configuration for creating or updating a tenant notification template + + published: Whether to publish the template immediately after saving. When true, the + template becomes the active/published version. When false (default), the + template is saved as a draft. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + return await self._put( + path_template("/tenants/{tenant_id}/templates/{template_id}", tenant_id=tenant_id, template_id=template_id), + body=await async_maybe_transform( + { + "template": template, + "published": published, + }, + template_replace_params.TemplateReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PutTenantTemplateResponse, + ) + + +class TemplatesResourceWithRawResponse: + def __init__(self, templates: TemplatesResource) -> None: + self._templates = templates + + self.retrieve = to_raw_response_wrapper( + templates.retrieve, + ) + self.list = to_raw_response_wrapper( + templates.list, + ) + self.delete = to_raw_response_wrapper( + templates.delete, + ) + self.publish = to_raw_response_wrapper( + templates.publish, + ) + self.replace = to_raw_response_wrapper( + templates.replace, + ) + + @cached_property + def versions(self) -> VersionsResourceWithRawResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return VersionsResourceWithRawResponse(self._templates.versions) + + +class AsyncTemplatesResourceWithRawResponse: + def __init__(self, templates: AsyncTemplatesResource) -> None: + self._templates = templates + + self.retrieve = async_to_raw_response_wrapper( + templates.retrieve, + ) + self.list = async_to_raw_response_wrapper( + templates.list, + ) + self.delete = async_to_raw_response_wrapper( + templates.delete, + ) + self.publish = async_to_raw_response_wrapper( + templates.publish, + ) + self.replace = async_to_raw_response_wrapper( + templates.replace, + ) + + @cached_property + def versions(self) -> AsyncVersionsResourceWithRawResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return AsyncVersionsResourceWithRawResponse(self._templates.versions) + + +class TemplatesResourceWithStreamingResponse: + def __init__(self, templates: TemplatesResource) -> None: + self._templates = templates + + self.retrieve = to_streamed_response_wrapper( + templates.retrieve, + ) + self.list = to_streamed_response_wrapper( + templates.list, + ) + self.delete = to_streamed_response_wrapper( + templates.delete, + ) + self.publish = to_streamed_response_wrapper( + templates.publish, + ) + self.replace = to_streamed_response_wrapper( + templates.replace, + ) + + @cached_property + def versions(self) -> VersionsResourceWithStreamingResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return VersionsResourceWithStreamingResponse(self._templates.versions) + + +class AsyncTemplatesResourceWithStreamingResponse: + def __init__(self, templates: AsyncTemplatesResource) -> None: + self._templates = templates + + self.retrieve = async_to_streamed_response_wrapper( + templates.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + templates.list, + ) + self.delete = async_to_streamed_response_wrapper( + templates.delete, + ) + self.publish = async_to_streamed_response_wrapper( + templates.publish, + ) + self.replace = async_to_streamed_response_wrapper( + templates.replace, + ) + + @cached_property + def versions(self) -> AsyncVersionsResourceWithStreamingResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return AsyncVersionsResourceWithStreamingResponse(self._templates.versions) diff --git a/src/courier/resources/tenants/templates/versions.py b/src/courier/resources/tenants/templates/versions.py new file mode 100644 index 00000000..bd91faa9 --- /dev/null +++ b/src/courier/resources/tenants/templates/versions.py @@ -0,0 +1,196 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ...._types import Body, Query, Headers, NotGiven, not_given +from ...._utils import path_template +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...._base_client import make_request_options +from ....types.base_template_tenant_association import BaseTemplateTenantAssociation + +__all__ = ["VersionsResource", "AsyncVersionsResource"] + + +class VersionsResource(SyncAPIResource): + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + + @cached_property + def with_raw_response(self) -> VersionsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return VersionsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> VersionsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return VersionsResourceWithStreamingResponse(self) + + def retrieve( + self, + version: str, + *, + tenant_id: str, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BaseTemplateTenantAssociation: + """ + Returns one version of a tenant template, addressed by version number or by + latest, with its content and publish timestamp. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not version: + raise ValueError(f"Expected a non-empty value for `version` but received {version!r}") + return self._get( + path_template( + "/tenants/{tenant_id}/templates/{template_id}/versions/{version}", + tenant_id=tenant_id, + template_id=template_id, + version=version, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BaseTemplateTenantAssociation, + ) + + +class AsyncVersionsResource(AsyncAPIResource): + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + + @cached_property + def with_raw_response(self) -> AsyncVersionsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncVersionsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncVersionsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncVersionsResourceWithStreamingResponse(self) + + async def retrieve( + self, + version: str, + *, + tenant_id: str, + template_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> BaseTemplateTenantAssociation: + """ + Returns one version of a tenant template, addressed by version number or by + latest, with its content and publish timestamp. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + if not template_id: + raise ValueError(f"Expected a non-empty value for `template_id` but received {template_id!r}") + if not version: + raise ValueError(f"Expected a non-empty value for `version` but received {version!r}") + return await self._get( + path_template( + "/tenants/{tenant_id}/templates/{template_id}/versions/{version}", + tenant_id=tenant_id, + template_id=template_id, + version=version, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=BaseTemplateTenantAssociation, + ) + + +class VersionsResourceWithRawResponse: + def __init__(self, versions: VersionsResource) -> None: + self._versions = versions + + self.retrieve = to_raw_response_wrapper( + versions.retrieve, + ) + + +class AsyncVersionsResourceWithRawResponse: + def __init__(self, versions: AsyncVersionsResource) -> None: + self._versions = versions + + self.retrieve = async_to_raw_response_wrapper( + versions.retrieve, + ) + + +class VersionsResourceWithStreamingResponse: + def __init__(self, versions: VersionsResource) -> None: + self._versions = versions + + self.retrieve = to_streamed_response_wrapper( + versions.retrieve, + ) + + +class AsyncVersionsResourceWithStreamingResponse: + def __init__(self, versions: AsyncVersionsResource) -> None: + self._versions = versions + + self.retrieve = async_to_streamed_response_wrapper( + versions.retrieve, + ) diff --git a/src/courier/resources/tenants/tenants.py b/src/courier/resources/tenants/tenants.py new file mode 100644 index 00000000..a05a830c --- /dev/null +++ b/src/courier/resources/tenants/tenants.py @@ -0,0 +1,714 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional + +import httpx + +from ...types import tenant_list_params, tenant_update_params, tenant_list_users_params +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.tenant import Tenant +from .templates.templates import ( + TemplatesResource, + AsyncTemplatesResource, + TemplatesResourceWithRawResponse, + AsyncTemplatesResourceWithRawResponse, + TemplatesResourceWithStreamingResponse, + AsyncTemplatesResourceWithStreamingResponse, +) +from .preferences.preferences import ( + PreferencesResource, + AsyncPreferencesResource, + PreferencesResourceWithRawResponse, + AsyncPreferencesResourceWithRawResponse, + PreferencesResourceWithStreamingResponse, + AsyncPreferencesResourceWithStreamingResponse, +) +from ...types.tenant_list_response import TenantListResponse +from ...types.default_preferences_param import DefaultPreferencesParam +from ...types.tenant_list_users_response import TenantListUsersResponse + +__all__ = ["TenantsResource", "AsyncTenantsResource"] + + +class TenantsResource(SyncAPIResource): + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + + @cached_property + def preferences(self) -> PreferencesResource: + return PreferencesResource(self._client) + + @cached_property + def templates(self) -> TemplatesResource: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return TemplatesResource(self._client) + + @cached_property + def with_raw_response(self) -> TenantsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TenantsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TenantsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TenantsResourceWithStreamingResponse(self) + + def retrieve( + self, + tenant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Tenant: + """ + Returns one tenant with its name, parent tenant id, default preferences, + properties, and the user profile applied to its members. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return self._get( + path_template("/tenants/{tenant_id}", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Tenant, + ) + + def update( + self, + tenant_id: str, + *, + name: str, + brand_id: Optional[str] | Omit = omit, + default_preferences: Optional[DefaultPreferencesParam] | Omit = omit, + parent_tenant_id: Optional[str] | Omit = omit, + properties: Optional[Dict[str, object]] | Omit = omit, + user_profile: Optional[Dict[str, object]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Tenant: + """ + Creates or replaces a tenant from a name, parent, brand, properties, and default + preferences supplied in the request body. + + Args: + name: Name of the tenant. + + brand_id: Brand to be used for the account when one is not specified by the send call. + + default_preferences: Defines the preferences used for the tenant when the user hasn't specified their + own. + + parent_tenant_id: Tenant's parent id (if any). + + properties: Arbitrary properties accessible to a template. + + user_profile: A user profile object merged with user profile on send. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return self._put( + path_template("/tenants/{tenant_id}", tenant_id=tenant_id), + body=maybe_transform( + { + "name": name, + "brand_id": brand_id, + "default_preferences": default_preferences, + "parent_tenant_id": parent_tenant_id, + "properties": properties, + "user_profile": user_profile, + }, + tenant_update_params.TenantUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Tenant, + ) + + def list( + self, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + parent_tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TenantListResponse: + """ + Lists the workspace's tenants, each carrying a name, parent tenant, properties, + and default preferences. Paged. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of tenants to return (defaults to 20, maximum value of 100) + + parent_tenant_id: Filter the list of tenants by parent_id + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + "/tenants", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + "parent_tenant_id": parent_tenant_id, + }, + tenant_list_params.TenantListParams, + ), + ), + cast_to=TenantListResponse, + ) + + def delete( + self, + tenant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a tenant. + + Its members' workspace-level profiles and preferences live + outside the tenant and are managed separately. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/tenants/{tenant_id}", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def list_users( + self, + tenant_id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TenantListUsersResponse: + """Returns the users belonging to a tenant with cursor paging. + + Use it to see who a + tenant-scoped send will reach. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of accounts to return (defaults to 20, maximum value of 100) + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return self._get( + path_template("/tenants/{tenant_id}/users", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + tenant_list_users_params.TenantListUsersParams, + ), + ), + cast_to=TenantListUsersResponse, + ) + + +class AsyncTenantsResource(AsyncAPIResource): + """ + Manage tenants — the organizations, teams, or accounts your users belong to — along with their users and default preferences. + """ + + @cached_property + def preferences(self) -> AsyncPreferencesResource: + return AsyncPreferencesResource(self._client) + + @cached_property + def templates(self) -> AsyncTemplatesResource: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return AsyncTemplatesResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncTenantsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTenantsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTenantsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTenantsResourceWithStreamingResponse(self) + + async def retrieve( + self, + tenant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Tenant: + """ + Returns one tenant with its name, parent tenant id, default preferences, + properties, and the user profile applied to its members. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return await self._get( + path_template("/tenants/{tenant_id}", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Tenant, + ) + + async def update( + self, + tenant_id: str, + *, + name: str, + brand_id: Optional[str] | Omit = omit, + default_preferences: Optional[DefaultPreferencesParam] | Omit = omit, + parent_tenant_id: Optional[str] | Omit = omit, + properties: Optional[Dict[str, object]] | Omit = omit, + user_profile: Optional[Dict[str, object]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> Tenant: + """ + Creates or replaces a tenant from a name, parent, brand, properties, and default + preferences supplied in the request body. + + Args: + name: Name of the tenant. + + brand_id: Brand to be used for the account when one is not specified by the send call. + + default_preferences: Defines the preferences used for the tenant when the user hasn't specified their + own. + + parent_tenant_id: Tenant's parent id (if any). + + properties: Arbitrary properties accessible to a template. + + user_profile: A user profile object merged with user profile on send. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return await self._put( + path_template("/tenants/{tenant_id}", tenant_id=tenant_id), + body=await async_maybe_transform( + { + "name": name, + "brand_id": brand_id, + "default_preferences": default_preferences, + "parent_tenant_id": parent_tenant_id, + "properties": properties, + "user_profile": user_profile, + }, + tenant_update_params.TenantUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Tenant, + ) + + async def list( + self, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + parent_tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TenantListResponse: + """ + Lists the workspace's tenants, each carrying a name, parent tenant, properties, + and default preferences. Paged. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of tenants to return (defaults to 20, maximum value of 100) + + parent_tenant_id: Filter the list of tenants by parent_id + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + "/tenants", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + "parent_tenant_id": parent_tenant_id, + }, + tenant_list_params.TenantListParams, + ), + ), + cast_to=TenantListResponse, + ) + + async def delete( + self, + tenant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Deletes a tenant. + + Its members' workspace-level profiles and preferences live + outside the tenant and are managed separately. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/tenants/{tenant_id}", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def list_users( + self, + tenant_id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TenantListUsersResponse: + """Returns the users belonging to a tenant with cursor paging. + + Use it to see who a + tenant-scoped send will reach. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of accounts to return (defaults to 20, maximum value of 100) + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + return await self._get( + path_template("/tenants/{tenant_id}/users", tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + tenant_list_users_params.TenantListUsersParams, + ), + ), + cast_to=TenantListUsersResponse, + ) + + +class TenantsResourceWithRawResponse: + def __init__(self, tenants: TenantsResource) -> None: + self._tenants = tenants + + self.retrieve = to_raw_response_wrapper( + tenants.retrieve, + ) + self.update = to_raw_response_wrapper( + tenants.update, + ) + self.list = to_raw_response_wrapper( + tenants.list, + ) + self.delete = to_raw_response_wrapper( + tenants.delete, + ) + self.list_users = to_raw_response_wrapper( + tenants.list_users, + ) + + @cached_property + def preferences(self) -> PreferencesResourceWithRawResponse: + return PreferencesResourceWithRawResponse(self._tenants.preferences) + + @cached_property + def templates(self) -> TemplatesResourceWithRawResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return TemplatesResourceWithRawResponse(self._tenants.templates) + + +class AsyncTenantsResourceWithRawResponse: + def __init__(self, tenants: AsyncTenantsResource) -> None: + self._tenants = tenants + + self.retrieve = async_to_raw_response_wrapper( + tenants.retrieve, + ) + self.update = async_to_raw_response_wrapper( + tenants.update, + ) + self.list = async_to_raw_response_wrapper( + tenants.list, + ) + self.delete = async_to_raw_response_wrapper( + tenants.delete, + ) + self.list_users = async_to_raw_response_wrapper( + tenants.list_users, + ) + + @cached_property + def preferences(self) -> AsyncPreferencesResourceWithRawResponse: + return AsyncPreferencesResourceWithRawResponse(self._tenants.preferences) + + @cached_property + def templates(self) -> AsyncTemplatesResourceWithRawResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return AsyncTemplatesResourceWithRawResponse(self._tenants.templates) + + +class TenantsResourceWithStreamingResponse: + def __init__(self, tenants: TenantsResource) -> None: + self._tenants = tenants + + self.retrieve = to_streamed_response_wrapper( + tenants.retrieve, + ) + self.update = to_streamed_response_wrapper( + tenants.update, + ) + self.list = to_streamed_response_wrapper( + tenants.list, + ) + self.delete = to_streamed_response_wrapper( + tenants.delete, + ) + self.list_users = to_streamed_response_wrapper( + tenants.list_users, + ) + + @cached_property + def preferences(self) -> PreferencesResourceWithStreamingResponse: + return PreferencesResourceWithStreamingResponse(self._tenants.preferences) + + @cached_property + def templates(self) -> TemplatesResourceWithStreamingResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return TemplatesResourceWithStreamingResponse(self._tenants.templates) + + +class AsyncTenantsResourceWithStreamingResponse: + def __init__(self, tenants: AsyncTenantsResource) -> None: + self._tenants = tenants + + self.retrieve = async_to_streamed_response_wrapper( + tenants.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + tenants.update, + ) + self.list = async_to_streamed_response_wrapper( + tenants.list, + ) + self.delete = async_to_streamed_response_wrapper( + tenants.delete, + ) + self.list_users = async_to_streamed_response_wrapper( + tenants.list_users, + ) + + @cached_property + def preferences(self) -> AsyncPreferencesResourceWithStreamingResponse: + return AsyncPreferencesResourceWithStreamingResponse(self._tenants.preferences) + + @cached_property + def templates(self) -> AsyncTemplatesResourceWithStreamingResponse: + """ + Manage the templates and template versions scoped to a single tenant, including the ones authored in the embedded designer. + """ + return AsyncTemplatesResourceWithStreamingResponse(self._tenants.templates) diff --git a/src/courier/resources/translations.py b/src/courier/resources/translations.py new file mode 100644 index 00000000..dc20557c --- /dev/null +++ b/src/courier/resources/translations.py @@ -0,0 +1,274 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from ..types import translation_update_params +from .._types import Body, Query, Headers, NoneType, NotGiven, not_given +from .._utils import path_template, maybe_transform, async_maybe_transform +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from .._base_client import make_request_options + +__all__ = ["TranslationsResource", "AsyncTranslationsResource"] + + +class TranslationsResource(SyncAPIResource): + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + + @cached_property + def with_raw_response(self) -> TranslationsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TranslationsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TranslationsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TranslationsResourceWithStreamingResponse(self) + + def retrieve( + self, + locale: str, + *, + domain: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> str: + """ + Returns the translation strings stored for one domain and locale, for use in + localized notification content. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not domain: + raise ValueError(f"Expected a non-empty value for `domain` but received {domain!r}") + if not locale: + raise ValueError(f"Expected a non-empty value for `locale` but received {locale!r}") + return self._get( + path_template("/translations/{domain}/{locale}", domain=domain, locale=locale), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=str, + ) + + def update( + self, + locale: str, + *, + domain: str, + body: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Uploads the translation strings for one domain and locale. + + Courier uses them to + render localized content for recipients in that locale. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not domain: + raise ValueError(f"Expected a non-empty value for `domain` but received {domain!r}") + if not locale: + raise ValueError(f"Expected a non-empty value for `locale` but received {locale!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/translations/{domain}/{locale}", domain=domain, locale=locale), + body=maybe_transform(body, translation_update_params.TranslationUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncTranslationsResource(AsyncAPIResource): + """ + Store and retrieve the translation strings Courier uses to render localized template content. + """ + + @cached_property + def with_raw_response(self) -> AsyncTranslationsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTranslationsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTranslationsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTranslationsResourceWithStreamingResponse(self) + + async def retrieve( + self, + locale: str, + *, + domain: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> str: + """ + Returns the translation strings stored for one domain and locale, for use in + localized notification content. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not domain: + raise ValueError(f"Expected a non-empty value for `domain` but received {domain!r}") + if not locale: + raise ValueError(f"Expected a non-empty value for `locale` but received {locale!r}") + return await self._get( + path_template("/translations/{domain}/{locale}", domain=domain, locale=locale), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=str, + ) + + async def update( + self, + locale: str, + *, + domain: str, + body: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Uploads the translation strings for one domain and locale. + + Courier uses them to + render localized content for recipients in that locale. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not domain: + raise ValueError(f"Expected a non-empty value for `domain` but received {domain!r}") + if not locale: + raise ValueError(f"Expected a non-empty value for `locale` but received {locale!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/translations/{domain}/{locale}", domain=domain, locale=locale), + body=await async_maybe_transform(body, translation_update_params.TranslationUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class TranslationsResourceWithRawResponse: + def __init__(self, translations: TranslationsResource) -> None: + self._translations = translations + + self.retrieve = to_raw_response_wrapper( + translations.retrieve, + ) + self.update = to_raw_response_wrapper( + translations.update, + ) + + +class AsyncTranslationsResourceWithRawResponse: + def __init__(self, translations: AsyncTranslationsResource) -> None: + self._translations = translations + + self.retrieve = async_to_raw_response_wrapper( + translations.retrieve, + ) + self.update = async_to_raw_response_wrapper( + translations.update, + ) + + +class TranslationsResourceWithStreamingResponse: + def __init__(self, translations: TranslationsResource) -> None: + self._translations = translations + + self.retrieve = to_streamed_response_wrapper( + translations.retrieve, + ) + self.update = to_streamed_response_wrapper( + translations.update, + ) + + +class AsyncTranslationsResourceWithStreamingResponse: + def __init__(self, translations: AsyncTranslationsResource) -> None: + self._translations = translations + + self.retrieve = async_to_streamed_response_wrapper( + translations.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + translations.update, + ) diff --git a/src/courier/resources/users/__init__.py b/src/courier/resources/users/__init__.py new file mode 100644 index 00000000..f164052a --- /dev/null +++ b/src/courier/resources/users/__init__.py @@ -0,0 +1,61 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .users import ( + UsersResource, + AsyncUsersResource, + UsersResourceWithRawResponse, + AsyncUsersResourceWithRawResponse, + UsersResourceWithStreamingResponse, + AsyncUsersResourceWithStreamingResponse, +) +from .tokens import ( + TokensResource, + AsyncTokensResource, + TokensResourceWithRawResponse, + AsyncTokensResourceWithRawResponse, + TokensResourceWithStreamingResponse, + AsyncTokensResourceWithStreamingResponse, +) +from .tenants import ( + TenantsResource, + AsyncTenantsResource, + TenantsResourceWithRawResponse, + AsyncTenantsResourceWithRawResponse, + TenantsResourceWithStreamingResponse, + AsyncTenantsResourceWithStreamingResponse, +) +from .preferences import ( + PreferencesResource, + AsyncPreferencesResource, + PreferencesResourceWithRawResponse, + AsyncPreferencesResourceWithRawResponse, + PreferencesResourceWithStreamingResponse, + AsyncPreferencesResourceWithStreamingResponse, +) + +__all__ = [ + "PreferencesResource", + "AsyncPreferencesResource", + "PreferencesResourceWithRawResponse", + "AsyncPreferencesResourceWithRawResponse", + "PreferencesResourceWithStreamingResponse", + "AsyncPreferencesResourceWithStreamingResponse", + "TenantsResource", + "AsyncTenantsResource", + "TenantsResourceWithRawResponse", + "AsyncTenantsResourceWithRawResponse", + "TenantsResourceWithStreamingResponse", + "AsyncTenantsResourceWithStreamingResponse", + "TokensResource", + "AsyncTokensResource", + "TokensResourceWithRawResponse", + "AsyncTokensResourceWithRawResponse", + "TokensResourceWithStreamingResponse", + "AsyncTokensResourceWithStreamingResponse", + "UsersResource", + "AsyncUsersResource", + "UsersResourceWithRawResponse", + "AsyncUsersResourceWithRawResponse", + "UsersResourceWithStreamingResponse", + "AsyncUsersResourceWithStreamingResponse", +] diff --git a/src/courier/resources/users/preferences.py b/src/courier/resources/users/preferences.py new file mode 100644 index 00000000..61d18743 --- /dev/null +++ b/src/courier/resources/users/preferences.py @@ -0,0 +1,774 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional + +import httpx + +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...types.users import ( + preference_retrieve_params, + preference_bulk_update_params, + preference_bulk_replace_params, + preference_delete_topic_params, + preference_retrieve_topic_params, + preference_update_or_create_topic_params, +) +from ..._base_client import make_request_options +from ...types.users.preference_retrieve_response import PreferenceRetrieveResponse +from ...types.users.preference_bulk_update_response import PreferenceBulkUpdateResponse +from ...types.users.preference_bulk_replace_response import PreferenceBulkReplaceResponse +from ...types.users.preference_retrieve_topic_response import PreferenceRetrieveTopicResponse +from ...types.users.preference_update_or_create_topic_response import PreferenceUpdateOrCreateTopicResponse + +__all__ = ["PreferencesResource", "AsyncPreferencesResource"] + + +class PreferencesResource(SyncAPIResource): + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + + @cached_property + def with_raw_response(self) -> PreferencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return PreferencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> PreferencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return PreferencesResourceWithStreamingResponse(self) + + def retrieve( + self, + user_id: str, + *, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceRetrieveResponse: + """ + Returns a user's preference overrides with paging, one entry per subscription + topic they have set a choice for. + + Args: + tenant_id: Query the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._get( + path_template("/users/{user_id}/preferences", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"tenant_id": tenant_id}, preference_retrieve_params.PreferenceRetrieveParams), + ), + cast_to=PreferenceRetrieveResponse, + ) + + def bulk_replace( + self, + user_id: str, + *, + topics: Iterable[preference_bulk_replace_params.Topic], + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceBulkReplaceResponse: + """Replaces a user's entire set of preference overrides. + + Any topic you leave out is + reset to its default, so send the full set rather than a subset. + + Args: + topics: The complete set of topic overrides for the user. Up to 50 topics may be + provided. Any existing override not listed here is reset to its topic default; + an empty array resets every existing override. + + tenant_id: Replace the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._put( + path_template("/users/{user_id}/preferences", user_id=user_id), + body=maybe_transform({"topics": topics}, preference_bulk_replace_params.PreferenceBulkReplaceParams), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"tenant_id": tenant_id}, preference_bulk_replace_params.PreferenceBulkReplaceParams + ), + ), + cast_to=PreferenceBulkReplaceResponse, + ) + + def bulk_update( + self, + user_id: str, + *, + topics: Iterable[preference_bulk_update_params.Topic], + tenant_id: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceBulkUpdateResponse: + """ + Adds or updates a user's preferences for several subscription topics at once. + Topics you leave out keep whatever they were set to before. + + Args: + topics: The topics to create or update. Between 1 and 50 topics may be provided in a + single request. + + tenant_id: Update the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/users/{user_id}/preferences", user_id=user_id), + body=maybe_transform({"topics": topics}, preference_bulk_update_params.PreferenceBulkUpdateParams), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"tenant_id": tenant_id}, preference_bulk_update_params.PreferenceBulkUpdateParams + ), + ), + cast_to=PreferenceBulkUpdateResponse, + ) + + def delete_topic( + self, + topic_id: str, + *, + user_id: str, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Removes a user's override for one subscription topic, resetting it to the + effective default from the tenant or workspace. + + Args: + tenant_id: Delete the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/users/{user_id}/preferences/{topic_id}", user_id=user_id, topic_id=topic_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"tenant_id": tenant_id}, preference_delete_topic_params.PreferenceDeleteTopicParams + ), + ), + cast_to=NoneType, + ) + + def retrieve_topic( + self, + topic_id: str, + *, + user_id: str, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceRetrieveTopicResponse: + """ + Returns a user's opt-in status and channel choices for one subscription topic, + or the effective default if they have set no override. + + Args: + tenant_id: Query the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return self._get( + path_template("/users/{user_id}/preferences/{topic_id}", user_id=user_id, topic_id=topic_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"tenant_id": tenant_id}, preference_retrieve_topic_params.PreferenceRetrieveTopicParams + ), + ), + cast_to=PreferenceRetrieveTopicResponse, + ) + + def update_or_create_topic( + self, + topic_id: str, + *, + user_id: str, + topic: preference_update_or_create_topic_params.Topic, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceUpdateOrCreateTopicResponse: + """ + Sets a user's opt-in status and channel choices for one subscription topic, + overriding the tenant default for that topic only. + + Args: + tenant_id: Update the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return self._put( + path_template("/users/{user_id}/preferences/{topic_id}", user_id=user_id, topic_id=topic_id), + body=maybe_transform( + {"topic": topic}, preference_update_or_create_topic_params.PreferenceUpdateOrCreateTopicParams + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + {"tenant_id": tenant_id}, + preference_update_or_create_topic_params.PreferenceUpdateOrCreateTopicParams, + ), + ), + cast_to=PreferenceUpdateOrCreateTopicResponse, + ) + + +class AsyncPreferencesResource(AsyncAPIResource): + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + + @cached_property + def with_raw_response(self) -> AsyncPreferencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncPreferencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncPreferencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncPreferencesResourceWithStreamingResponse(self) + + async def retrieve( + self, + user_id: str, + *, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceRetrieveResponse: + """ + Returns a user's preference overrides with paging, one entry per subscription + topic they have set a choice for. + + Args: + tenant_id: Query the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._get( + path_template("/users/{user_id}/preferences", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"tenant_id": tenant_id}, preference_retrieve_params.PreferenceRetrieveParams + ), + ), + cast_to=PreferenceRetrieveResponse, + ) + + async def bulk_replace( + self, + user_id: str, + *, + topics: Iterable[preference_bulk_replace_params.Topic], + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceBulkReplaceResponse: + """Replaces a user's entire set of preference overrides. + + Any topic you leave out is + reset to its default, so send the full set rather than a subset. + + Args: + topics: The complete set of topic overrides for the user. Up to 50 topics may be + provided. Any existing override not listed here is reset to its topic default; + an empty array resets every existing override. + + tenant_id: Replace the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._put( + path_template("/users/{user_id}/preferences", user_id=user_id), + body=await async_maybe_transform( + {"topics": topics}, preference_bulk_replace_params.PreferenceBulkReplaceParams + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"tenant_id": tenant_id}, preference_bulk_replace_params.PreferenceBulkReplaceParams + ), + ), + cast_to=PreferenceBulkReplaceResponse, + ) + + async def bulk_update( + self, + user_id: str, + *, + topics: Iterable[preference_bulk_update_params.Topic], + tenant_id: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceBulkUpdateResponse: + """ + Adds or updates a user's preferences for several subscription topics at once. + Topics you leave out keep whatever they were set to before. + + Args: + topics: The topics to create or update. Between 1 and 50 topics may be provided in a + single request. + + tenant_id: Update the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/users/{user_id}/preferences", user_id=user_id), + body=await async_maybe_transform( + {"topics": topics}, preference_bulk_update_params.PreferenceBulkUpdateParams + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"tenant_id": tenant_id}, preference_bulk_update_params.PreferenceBulkUpdateParams + ), + ), + cast_to=PreferenceBulkUpdateResponse, + ) + + async def delete_topic( + self, + topic_id: str, + *, + user_id: str, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Removes a user's override for one subscription topic, resetting it to the + effective default from the tenant or workspace. + + Args: + tenant_id: Delete the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/users/{user_id}/preferences/{topic_id}", user_id=user_id, topic_id=topic_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"tenant_id": tenant_id}, preference_delete_topic_params.PreferenceDeleteTopicParams + ), + ), + cast_to=NoneType, + ) + + async def retrieve_topic( + self, + topic_id: str, + *, + user_id: str, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceRetrieveTopicResponse: + """ + Returns a user's opt-in status and channel choices for one subscription topic, + or the effective default if they have set no override. + + Args: + tenant_id: Query the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return await self._get( + path_template("/users/{user_id}/preferences/{topic_id}", user_id=user_id, topic_id=topic_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"tenant_id": tenant_id}, preference_retrieve_topic_params.PreferenceRetrieveTopicParams + ), + ), + cast_to=PreferenceRetrieveTopicResponse, + ) + + async def update_or_create_topic( + self, + topic_id: str, + *, + user_id: str, + topic: preference_update_or_create_topic_params.Topic, + tenant_id: Optional[str] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PreferenceUpdateOrCreateTopicResponse: + """ + Sets a user's opt-in status and channel choices for one subscription topic, + overriding the tenant default for that topic only. + + Args: + tenant_id: Update the preferences of a user for this specific tenant context. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return await self._put( + path_template("/users/{user_id}/preferences/{topic_id}", user_id=user_id, topic_id=topic_id), + body=await async_maybe_transform( + {"topic": topic}, preference_update_or_create_topic_params.PreferenceUpdateOrCreateTopicParams + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"tenant_id": tenant_id}, + preference_update_or_create_topic_params.PreferenceUpdateOrCreateTopicParams, + ), + ), + cast_to=PreferenceUpdateOrCreateTopicResponse, + ) + + +class PreferencesResourceWithRawResponse: + def __init__(self, preferences: PreferencesResource) -> None: + self._preferences = preferences + + self.retrieve = to_raw_response_wrapper( + preferences.retrieve, + ) + self.bulk_replace = to_raw_response_wrapper( + preferences.bulk_replace, + ) + self.bulk_update = to_raw_response_wrapper( + preferences.bulk_update, + ) + self.delete_topic = to_raw_response_wrapper( + preferences.delete_topic, + ) + self.retrieve_topic = to_raw_response_wrapper( + preferences.retrieve_topic, + ) + self.update_or_create_topic = to_raw_response_wrapper( + preferences.update_or_create_topic, + ) + + +class AsyncPreferencesResourceWithRawResponse: + def __init__(self, preferences: AsyncPreferencesResource) -> None: + self._preferences = preferences + + self.retrieve = async_to_raw_response_wrapper( + preferences.retrieve, + ) + self.bulk_replace = async_to_raw_response_wrapper( + preferences.bulk_replace, + ) + self.bulk_update = async_to_raw_response_wrapper( + preferences.bulk_update, + ) + self.delete_topic = async_to_raw_response_wrapper( + preferences.delete_topic, + ) + self.retrieve_topic = async_to_raw_response_wrapper( + preferences.retrieve_topic, + ) + self.update_or_create_topic = async_to_raw_response_wrapper( + preferences.update_or_create_topic, + ) + + +class PreferencesResourceWithStreamingResponse: + def __init__(self, preferences: PreferencesResource) -> None: + self._preferences = preferences + + self.retrieve = to_streamed_response_wrapper( + preferences.retrieve, + ) + self.bulk_replace = to_streamed_response_wrapper( + preferences.bulk_replace, + ) + self.bulk_update = to_streamed_response_wrapper( + preferences.bulk_update, + ) + self.delete_topic = to_streamed_response_wrapper( + preferences.delete_topic, + ) + self.retrieve_topic = to_streamed_response_wrapper( + preferences.retrieve_topic, + ) + self.update_or_create_topic = to_streamed_response_wrapper( + preferences.update_or_create_topic, + ) + + +class AsyncPreferencesResourceWithStreamingResponse: + def __init__(self, preferences: AsyncPreferencesResource) -> None: + self._preferences = preferences + + self.retrieve = async_to_streamed_response_wrapper( + preferences.retrieve, + ) + self.bulk_replace = async_to_streamed_response_wrapper( + preferences.bulk_replace, + ) + self.bulk_update = async_to_streamed_response_wrapper( + preferences.bulk_update, + ) + self.delete_topic = async_to_streamed_response_wrapper( + preferences.delete_topic, + ) + self.retrieve_topic = async_to_streamed_response_wrapper( + preferences.retrieve_topic, + ) + self.update_or_create_topic = async_to_streamed_response_wrapper( + preferences.update_or_create_topic, + ) diff --git a/src/courier/resources/users/tenants.py b/src/courier/resources/users/tenants.py new file mode 100644 index 00000000..b7b13102 --- /dev/null +++ b/src/courier/resources/users/tenants.py @@ -0,0 +1,564 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Iterable, Optional + +import httpx + +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...types.users import tenant_list_params, tenant_add_single_params, tenant_add_multiple_params +from ..._base_client import make_request_options +from ...types.tenant_association_param import TenantAssociationParam +from ...types.users.tenant_list_response import TenantListResponse + +__all__ = ["TenantsResource", "AsyncTenantsResource"] + + +class TenantsResource(SyncAPIResource): + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + + @cached_property + def with_raw_response(self) -> TenantsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TenantsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TenantsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TenantsResourceWithStreamingResponse(self) + + def list( + self, + user_id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TenantListResponse: + """Returns the tenants a user belongs to, with cursor paging. + + A user can belong to + many tenants, each with its own profile and preferences. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of accounts to return (defaults to 20, maximum value of 100) + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._get( + path_template("/users/{user_id}/tenants", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + tenant_list_params.TenantListParams, + ), + ), + cast_to=TenantListResponse, + ) + + def add_multiple( + self, + user_id: str, + *, + tenants: Iterable[TenantAssociationParam], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Adds a user to several tenants in one call, each optionally with a per-tenant + profile that overrides their workspace profile. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/users/{user_id}/tenants", user_id=user_id), + body=maybe_transform({"tenants": tenants}, tenant_add_multiple_params.TenantAddMultipleParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def add_single( + self, + tenant_id: str, + *, + user_id: str, + profile: Optional[Dict[str, object]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Adds a user to one tenant, optionally with a tenant-specific profile that + overrides their workspace profile for sends in that tenant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/users/{user_id}/tenants/{tenant_id}", user_id=user_id, tenant_id=tenant_id), + body=maybe_transform({"profile": profile}, tenant_add_single_params.TenantAddSingleParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def remove_all( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Removes a user from every tenant they belong to in one call. + + Their + workspace-level profile is a separate resource. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/users/{user_id}/tenants", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def remove_single( + self, + tenant_id: str, + *, + user_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Removes a user from one tenant. + + Their other tenant memberships and workspace + profile are managed through separate endpoints. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/users/{user_id}/tenants/{tenant_id}", user_id=user_id, tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncTenantsResource(AsyncAPIResource): + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + + @cached_property + def with_raw_response(self) -> AsyncTenantsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTenantsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTenantsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTenantsResourceWithStreamingResponse(self) + + async def list( + self, + user_id: str, + *, + cursor: Optional[str] | Omit = omit, + limit: Optional[int] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TenantListResponse: + """Returns the tenants a user belongs to, with cursor paging. + + A user can belong to + many tenants, each with its own profile and preferences. + + Args: + cursor: Continue the pagination with the next cursor + + limit: The number of accounts to return (defaults to 20, maximum value of 100) + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._get( + path_template("/users/{user_id}/tenants", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "cursor": cursor, + "limit": limit, + }, + tenant_list_params.TenantListParams, + ), + ), + cast_to=TenantListResponse, + ) + + async def add_multiple( + self, + user_id: str, + *, + tenants: Iterable[TenantAssociationParam], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Adds a user to several tenants in one call, each optionally with a per-tenant + profile that overrides their workspace profile. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/users/{user_id}/tenants", user_id=user_id), + body=await async_maybe_transform({"tenants": tenants}, tenant_add_multiple_params.TenantAddMultipleParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def add_single( + self, + tenant_id: str, + *, + user_id: str, + profile: Optional[Dict[str, object]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Adds a user to one tenant, optionally with a tenant-specific profile that + overrides their workspace profile for sends in that tenant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/users/{user_id}/tenants/{tenant_id}", user_id=user_id, tenant_id=tenant_id), + body=await async_maybe_transform({"profile": profile}, tenant_add_single_params.TenantAddSingleParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def remove_all( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Removes a user from every tenant they belong to in one call. + + Their + workspace-level profile is a separate resource. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/users/{user_id}/tenants", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def remove_single( + self, + tenant_id: str, + *, + user_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Removes a user from one tenant. + + Their other tenant memberships and workspace + profile are managed through separate endpoints. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not tenant_id: + raise ValueError(f"Expected a non-empty value for `tenant_id` but received {tenant_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/users/{user_id}/tenants/{tenant_id}", user_id=user_id, tenant_id=tenant_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class TenantsResourceWithRawResponse: + def __init__(self, tenants: TenantsResource) -> None: + self._tenants = tenants + + self.list = to_raw_response_wrapper( + tenants.list, + ) + self.add_multiple = to_raw_response_wrapper( + tenants.add_multiple, + ) + self.add_single = to_raw_response_wrapper( + tenants.add_single, + ) + self.remove_all = to_raw_response_wrapper( + tenants.remove_all, + ) + self.remove_single = to_raw_response_wrapper( + tenants.remove_single, + ) + + +class AsyncTenantsResourceWithRawResponse: + def __init__(self, tenants: AsyncTenantsResource) -> None: + self._tenants = tenants + + self.list = async_to_raw_response_wrapper( + tenants.list, + ) + self.add_multiple = async_to_raw_response_wrapper( + tenants.add_multiple, + ) + self.add_single = async_to_raw_response_wrapper( + tenants.add_single, + ) + self.remove_all = async_to_raw_response_wrapper( + tenants.remove_all, + ) + self.remove_single = async_to_raw_response_wrapper( + tenants.remove_single, + ) + + +class TenantsResourceWithStreamingResponse: + def __init__(self, tenants: TenantsResource) -> None: + self._tenants = tenants + + self.list = to_streamed_response_wrapper( + tenants.list, + ) + self.add_multiple = to_streamed_response_wrapper( + tenants.add_multiple, + ) + self.add_single = to_streamed_response_wrapper( + tenants.add_single, + ) + self.remove_all = to_streamed_response_wrapper( + tenants.remove_all, + ) + self.remove_single = to_streamed_response_wrapper( + tenants.remove_single, + ) + + +class AsyncTenantsResourceWithStreamingResponse: + def __init__(self, tenants: AsyncTenantsResource) -> None: + self._tenants = tenants + + self.list = async_to_streamed_response_wrapper( + tenants.list, + ) + self.add_multiple = async_to_streamed_response_wrapper( + tenants.add_multiple, + ) + self.add_single = async_to_streamed_response_wrapper( + tenants.add_single, + ) + self.remove_all = async_to_streamed_response_wrapper( + tenants.remove_all, + ) + self.remove_single = async_to_streamed_response_wrapper( + tenants.remove_single, + ) diff --git a/src/courier/resources/users/tokens.py b/src/courier/resources/users/tokens.py new file mode 100644 index 00000000..c43acb01 --- /dev/null +++ b/src/courier/resources/users/tokens.py @@ -0,0 +1,663 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable, Optional +from typing_extensions import Literal + +import httpx + +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ...types.users import token_update_params, token_add_single_params +from ..._base_client import make_request_options +from ...types.users.token_list_response import TokenListResponse +from ...types.users.token_retrieve_response import TokenRetrieveResponse + +__all__ = ["TokensResource", "AsyncTokensResource"] + + +class TokensResource(SyncAPIResource): + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + + @cached_property + def with_raw_response(self) -> TokensResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TokensResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TokensResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TokensResourceWithStreamingResponse(self) + + def retrieve( + self, + token: str, + *, + user_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TokenRetrieveResponse: + """ + Returns one device token with its provider key, status and status reason, expiry + date, and any properties stored alongside it. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + return self._get( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=TokenRetrieveResponse, + ) + + def update( + self, + token: str, + *, + user_id: str, + patch: Iterable[token_update_params.Patch], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Applies a JSON Patch to a device token, changing its status, expiry, or + properties without re-registering it. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._patch( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + body=maybe_transform({"patch": patch}, token_update_params.TokenUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def list( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TokenListResponse: + """ + Returns every device token registered for a user, each with its provider key, + status, and expiry date. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return self._get( + path_template("/users/{user_id}/tokens", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=TokenListResponse, + ) + + def delete( + self, + token: str, + *, + user_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Deletes one device token for a user, addressed by the token value, so push sends + no longer target that device. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def add_multiple( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Registers several device tokens for a user in one call, overwriting any stored + token with a matching value. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/users/{user_id}/tokens", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def add_single( + self, + token: str, + *, + user_id: str, + provider_key: Literal["firebase-fcm", "apn", "expo", "onesignal"], + device: Optional[token_add_single_params.Device] | Omit = omit, + expiry_date: Union[str, bool, None] | Omit = omit, + properties: object | Omit = omit, + tracking: Optional[token_add_single_params.Tracking] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Registers one device token for a user against a provider key, overwriting the + token if it already exists. Push sends resolve tokens per user. + + Args: + device: Information about the device the token came from. + + expiry_date: ISO 8601 formatted date the token expires. Defaults to 2 months. Set to false to + disable expiration. + + properties: Properties about the token. + + tracking: Tracking information about the device the token came from. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._put( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + body=maybe_transform( + { + "provider_key": provider_key, + "device": device, + "expiry_date": expiry_date, + "properties": properties, + "tracking": tracking, + }, + token_add_single_params.TokenAddSingleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncTokensResource(AsyncAPIResource): + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + + @cached_property + def with_raw_response(self) -> AsyncTokensResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTokensResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTokensResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTokensResourceWithStreamingResponse(self) + + async def retrieve( + self, + token: str, + *, + user_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TokenRetrieveResponse: + """ + Returns one device token with its provider key, status and status reason, expiry + date, and any properties stored alongside it. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + return await self._get( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=TokenRetrieveResponse, + ) + + async def update( + self, + token: str, + *, + user_id: str, + patch: Iterable[token_update_params.Patch], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Applies a JSON Patch to a device token, changing its status, expiry, or + properties without re-registering it. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._patch( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + body=await async_maybe_transform({"patch": patch}, token_update_params.TokenUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def list( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> TokenListResponse: + """ + Returns every device token registered for a user, each with its provider key, + status, and expiry date. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + return await self._get( + path_template("/users/{user_id}/tokens", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=TokenListResponse, + ) + + async def delete( + self, + token: str, + *, + user_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Deletes one device token for a user, addressed by the token value, so push sends + no longer target that device. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def add_multiple( + self, + user_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Registers several device tokens for a user in one call, overwriting any stored + token with a matching value. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/users/{user_id}/tokens", user_id=user_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def add_single( + self, + token: str, + *, + user_id: str, + provider_key: Literal["firebase-fcm", "apn", "expo", "onesignal"], + device: Optional[token_add_single_params.Device] | Omit = omit, + expiry_date: Union[str, bool, None] | Omit = omit, + properties: object | Omit = omit, + tracking: Optional[token_add_single_params.Tracking] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Registers one device token for a user against a provider key, overwriting the + token if it already exists. Push sends resolve tokens per user. + + Args: + device: Information about the device the token came from. + + expiry_date: ISO 8601 formatted date the token expires. Defaults to 2 months. Set to false to + disable expiration. + + properties: Properties about the token. + + tracking: Tracking information about the device the token came from. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not user_id: + raise ValueError(f"Expected a non-empty value for `user_id` but received {user_id!r}") + if not token: + raise ValueError(f"Expected a non-empty value for `token` but received {token!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._put( + path_template("/users/{user_id}/tokens/{token}", user_id=user_id, token=token), + body=await async_maybe_transform( + { + "provider_key": provider_key, + "device": device, + "expiry_date": expiry_date, + "properties": properties, + "tracking": tracking, + }, + token_add_single_params.TokenAddSingleParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class TokensResourceWithRawResponse: + def __init__(self, tokens: TokensResource) -> None: + self._tokens = tokens + + self.retrieve = to_raw_response_wrapper( + tokens.retrieve, + ) + self.update = to_raw_response_wrapper( + tokens.update, + ) + self.list = to_raw_response_wrapper( + tokens.list, + ) + self.delete = to_raw_response_wrapper( + tokens.delete, + ) + self.add_multiple = to_raw_response_wrapper( + tokens.add_multiple, + ) + self.add_single = to_raw_response_wrapper( + tokens.add_single, + ) + + +class AsyncTokensResourceWithRawResponse: + def __init__(self, tokens: AsyncTokensResource) -> None: + self._tokens = tokens + + self.retrieve = async_to_raw_response_wrapper( + tokens.retrieve, + ) + self.update = async_to_raw_response_wrapper( + tokens.update, + ) + self.list = async_to_raw_response_wrapper( + tokens.list, + ) + self.delete = async_to_raw_response_wrapper( + tokens.delete, + ) + self.add_multiple = async_to_raw_response_wrapper( + tokens.add_multiple, + ) + self.add_single = async_to_raw_response_wrapper( + tokens.add_single, + ) + + +class TokensResourceWithStreamingResponse: + def __init__(self, tokens: TokensResource) -> None: + self._tokens = tokens + + self.retrieve = to_streamed_response_wrapper( + tokens.retrieve, + ) + self.update = to_streamed_response_wrapper( + tokens.update, + ) + self.list = to_streamed_response_wrapper( + tokens.list, + ) + self.delete = to_streamed_response_wrapper( + tokens.delete, + ) + self.add_multiple = to_streamed_response_wrapper( + tokens.add_multiple, + ) + self.add_single = to_streamed_response_wrapper( + tokens.add_single, + ) + + +class AsyncTokensResourceWithStreamingResponse: + def __init__(self, tokens: AsyncTokensResource) -> None: + self._tokens = tokens + + self.retrieve = async_to_streamed_response_wrapper( + tokens.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + tokens.update, + ) + self.list = async_to_streamed_response_wrapper( + tokens.list, + ) + self.delete = async_to_streamed_response_wrapper( + tokens.delete, + ) + self.add_multiple = async_to_streamed_response_wrapper( + tokens.add_multiple, + ) + self.add_single = async_to_streamed_response_wrapper( + tokens.add_single, + ) diff --git a/src/courier/resources/users/users.py b/src/courier/resources/users/users.py new file mode 100644 index 00000000..9d080525 --- /dev/null +++ b/src/courier/resources/users/users.py @@ -0,0 +1,220 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .tokens import ( + TokensResource, + AsyncTokensResource, + TokensResourceWithRawResponse, + AsyncTokensResourceWithRawResponse, + TokensResourceWithStreamingResponse, + AsyncTokensResourceWithStreamingResponse, +) +from .tenants import ( + TenantsResource, + AsyncTenantsResource, + TenantsResourceWithRawResponse, + AsyncTenantsResourceWithRawResponse, + TenantsResourceWithStreamingResponse, + AsyncTenantsResourceWithStreamingResponse, +) +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from .preferences import ( + PreferencesResource, + AsyncPreferencesResource, + PreferencesResourceWithRawResponse, + AsyncPreferencesResourceWithRawResponse, + PreferencesResourceWithStreamingResponse, + AsyncPreferencesResourceWithStreamingResponse, +) + +__all__ = ["UsersResource", "AsyncUsersResource"] + + +class UsersResource(SyncAPIResource): + @cached_property + def preferences(self) -> PreferencesResource: + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + return PreferencesResource(self._client) + + @cached_property + def tenants(self) -> TenantsResource: + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + return TenantsResource(self._client) + + @cached_property + def tokens(self) -> TokensResource: + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + return TokensResource(self._client) + + @cached_property + def with_raw_response(self) -> UsersResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return UsersResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> UsersResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return UsersResourceWithStreamingResponse(self) + + +class AsyncUsersResource(AsyncAPIResource): + @cached_property + def preferences(self) -> AsyncPreferencesResource: + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + return AsyncPreferencesResource(self._client) + + @cached_property + def tenants(self) -> AsyncTenantsResource: + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + return AsyncTenantsResource(self._client) + + @cached_property + def tokens(self) -> AsyncTokensResource: + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + return AsyncTokensResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncUsersResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncUsersResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncUsersResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncUsersResourceWithStreamingResponse(self) + + +class UsersResourceWithRawResponse: + def __init__(self, users: UsersResource) -> None: + self._users = users + + @cached_property + def preferences(self) -> PreferencesResourceWithRawResponse: + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + return PreferencesResourceWithRawResponse(self._users.preferences) + + @cached_property + def tenants(self) -> TenantsResourceWithRawResponse: + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + return TenantsResourceWithRawResponse(self._users.tenants) + + @cached_property + def tokens(self) -> TokensResourceWithRawResponse: + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + return TokensResourceWithRawResponse(self._users.tokens) + + +class AsyncUsersResourceWithRawResponse: + def __init__(self, users: AsyncUsersResource) -> None: + self._users = users + + @cached_property + def preferences(self) -> AsyncPreferencesResourceWithRawResponse: + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + return AsyncPreferencesResourceWithRawResponse(self._users.preferences) + + @cached_property + def tenants(self) -> AsyncTenantsResourceWithRawResponse: + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + return AsyncTenantsResourceWithRawResponse(self._users.tenants) + + @cached_property + def tokens(self) -> AsyncTokensResourceWithRawResponse: + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + return AsyncTokensResourceWithRawResponse(self._users.tokens) + + +class UsersResourceWithStreamingResponse: + def __init__(self, users: UsersResource) -> None: + self._users = users + + @cached_property + def preferences(self) -> PreferencesResourceWithStreamingResponse: + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + return PreferencesResourceWithStreamingResponse(self._users.preferences) + + @cached_property + def tenants(self) -> TenantsResourceWithStreamingResponse: + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + return TenantsResourceWithStreamingResponse(self._users.tenants) + + @cached_property + def tokens(self) -> TokensResourceWithStreamingResponse: + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + return TokensResourceWithStreamingResponse(self._users.tokens) + + +class AsyncUsersResourceWithStreamingResponse: + def __init__(self, users: AsyncUsersResource) -> None: + self._users = users + + @cached_property + def preferences(self) -> AsyncPreferencesResourceWithStreamingResponse: + """ + Read and write a single user's notification preferences, per topic and per channel. + """ + return AsyncPreferencesResourceWithStreamingResponse(self._users.preferences) + + @cached_property + def tenants(self) -> AsyncTenantsResourceWithStreamingResponse: + """ + Associate a user with one or more tenants, and read or remove those associations. + """ + return AsyncTenantsResourceWithStreamingResponse(self._users.tenants) + + @cached_property + def tokens(self) -> AsyncTokensResourceWithStreamingResponse: + """ + Register and manage the APNS and FCM device tokens Courier delivers push notifications to. + """ + return AsyncTokensResourceWithStreamingResponse(self._users.tokens) diff --git a/src/courier/resources/workspace_preferences/__init__.py b/src/courier/resources/workspace_preferences/__init__.py new file mode 100644 index 00000000..21743d6b --- /dev/null +++ b/src/courier/resources/workspace_preferences/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .topics import ( + TopicsResource, + AsyncTopicsResource, + TopicsResourceWithRawResponse, + AsyncTopicsResourceWithRawResponse, + TopicsResourceWithStreamingResponse, + AsyncTopicsResourceWithStreamingResponse, +) +from .workspace_preferences import ( + WorkspacePreferencesResource, + AsyncWorkspacePreferencesResource, + WorkspacePreferencesResourceWithRawResponse, + AsyncWorkspacePreferencesResourceWithRawResponse, + WorkspacePreferencesResourceWithStreamingResponse, + AsyncWorkspacePreferencesResourceWithStreamingResponse, +) + +__all__ = [ + "TopicsResource", + "AsyncTopicsResource", + "TopicsResourceWithRawResponse", + "AsyncTopicsResourceWithRawResponse", + "TopicsResourceWithStreamingResponse", + "AsyncTopicsResourceWithStreamingResponse", + "WorkspacePreferencesResource", + "AsyncWorkspacePreferencesResource", + "WorkspacePreferencesResourceWithRawResponse", + "AsyncWorkspacePreferencesResourceWithRawResponse", + "WorkspacePreferencesResourceWithStreamingResponse", + "AsyncWorkspacePreferencesResourceWithStreamingResponse", +] diff --git a/src/courier/resources/workspace_preferences/topics.py b/src/courier/resources/workspace_preferences/topics.py new file mode 100644 index 00000000..2e9d5f3b --- /dev/null +++ b/src/courier/resources/workspace_preferences/topics.py @@ -0,0 +1,694 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Literal + +import httpx + +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.workspace_preferences import topic_create_params, topic_replace_params +from ...types.shared.channel_classification import ChannelClassification +from ...types.workspace_preference_topic_get_response import WorkspacePreferenceTopicGetResponse +from ...types.workspace_preference_topic_list_response import WorkspacePreferenceTopicListResponse + +__all__ = ["TopicsResource", "AsyncTopicsResource"] + + +class TopicsResource(SyncAPIResource): + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + + @cached_property + def with_raw_response(self) -> TopicsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return TopicsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TopicsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return TopicsResourceWithStreamingResponse(self) + + def create( + self, + section_id: str, + *, + default_status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"], + name: str, + allowed_preferences: Optional[List[Literal["snooze", "channel_preferences"]]] | Omit = omit, + description: Optional[str] | Omit = omit, + include_unsubscribe_header: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + topic_data: Optional[Dict[str, object]] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicGetResponse: + """Creates a subscription topic inside a workspace preference. + + The default status + sets whether users start opted in, opted out, or required. + + Args: + default_status: The default subscription status applied when a recipient has not set their own. + + name: Human-readable name for the preference topic. + + allowed_preferences: Preference controls a recipient may customize for this topic. Defaults to empty + if omitted. + + description: Optional description shown under the topic on the hosted preferences page. + + include_unsubscribe_header: Whether to include a list-unsubscribe header on emails for this topic. + + routing_options: Default channels delivered for this topic. Defaults to empty if omitted. + + topic_data: Arbitrary metadata associated with the topic. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + path_template("/preferences/sections/{section_id}/topics", section_id=section_id), + body=maybe_transform( + { + "default_status": default_status, + "name": name, + "allowed_preferences": allowed_preferences, + "description": description, + "include_unsubscribe_header": include_unsubscribe_header, + "routing_options": routing_options, + "topic_data": topic_data, + }, + topic_create_params.TopicCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicGetResponse, + ) + + def retrieve( + self, + topic_id: str, + *, + section_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicGetResponse: + """ + Returns one subscription topic with its default status, routing options, allowed + preferences, and unsubscribe header setting. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return self._get( + path_template( + "/preferences/sections/{section_id}/topics/{topic_id}", section_id=section_id, topic_id=topic_id + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicGetResponse, + ) + + def list( + self, + section_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicListResponse: + """ + Returns the subscription topics inside a workspace preference, each with its + default status and routing options. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + return self._get( + path_template("/preferences/sections/{section_id}/topics", section_id=section_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicListResponse, + ) + + def archive( + self, + topic_id: str, + *, + section_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Archives a subscription topic and removes it from its workspace preference, + addressed by section id and topic id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template( + "/preferences/sections/{section_id}/topics/{topic_id}", section_id=section_id, topic_id=topic_id + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def replace( + self, + topic_id: str, + *, + section_id: str, + default_status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"], + name: str, + allowed_preferences: Optional[List[Literal["snooze", "channel_preferences"]]] | Omit = omit, + description: Optional[str] | Omit = omit, + include_unsubscribe_header: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + topic_data: Optional[Dict[str, object]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicGetResponse: + """Replace a topic within a workspace preference. + + Full document replacement; + missing optional fields are cleared. Same 404 rules as GET. + + Args: + default_status: The default subscription status applied when a recipient has not set their own. + + name: Human-readable name for the preference topic. + + allowed_preferences: Preference controls a recipient may customize. Omit to clear. + + description: Optional description shown under the topic on the hosted preferences page. Omit + to clear. + + include_unsubscribe_header: Whether to include a list-unsubscribe header on emails for this topic. + + routing_options: Default channels delivered for this topic. Omit to clear. + + topic_data: Arbitrary metadata associated with the topic. Omit to clear. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return self._put( + path_template( + "/preferences/sections/{section_id}/topics/{topic_id}", section_id=section_id, topic_id=topic_id + ), + body=maybe_transform( + { + "default_status": default_status, + "name": name, + "allowed_preferences": allowed_preferences, + "description": description, + "include_unsubscribe_header": include_unsubscribe_header, + "routing_options": routing_options, + "topic_data": topic_data, + }, + topic_replace_params.TopicReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicGetResponse, + ) + + +class AsyncTopicsResource(AsyncAPIResource): + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + + @cached_property + def with_raw_response(self) -> AsyncTopicsResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncTopicsResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTopicsResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncTopicsResourceWithStreamingResponse(self) + + async def create( + self, + section_id: str, + *, + default_status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"], + name: str, + allowed_preferences: Optional[List[Literal["snooze", "channel_preferences"]]] | Omit = omit, + description: Optional[str] | Omit = omit, + include_unsubscribe_header: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + topic_data: Optional[Dict[str, object]] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicGetResponse: + """Creates a subscription topic inside a workspace preference. + + The default status + sets whether users start opted in, opted out, or required. + + Args: + default_status: The default subscription status applied when a recipient has not set their own. + + name: Human-readable name for the preference topic. + + allowed_preferences: Preference controls a recipient may customize for this topic. Defaults to empty + if omitted. + + description: Optional description shown under the topic on the hosted preferences page. + + include_unsubscribe_header: Whether to include a list-unsubscribe header on emails for this topic. + + routing_options: Default channels delivered for this topic. Defaults to empty if omitted. + + topic_data: Arbitrary metadata associated with the topic. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + path_template("/preferences/sections/{section_id}/topics", section_id=section_id), + body=await async_maybe_transform( + { + "default_status": default_status, + "name": name, + "allowed_preferences": allowed_preferences, + "description": description, + "include_unsubscribe_header": include_unsubscribe_header, + "routing_options": routing_options, + "topic_data": topic_data, + }, + topic_create_params.TopicCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicGetResponse, + ) + + async def retrieve( + self, + topic_id: str, + *, + section_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicGetResponse: + """ + Returns one subscription topic with its default status, routing options, allowed + preferences, and unsubscribe header setting. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return await self._get( + path_template( + "/preferences/sections/{section_id}/topics/{topic_id}", section_id=section_id, topic_id=topic_id + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicGetResponse, + ) + + async def list( + self, + section_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicListResponse: + """ + Returns the subscription topics inside a workspace preference, each with its + default status and routing options. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + return await self._get( + path_template("/preferences/sections/{section_id}/topics", section_id=section_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicListResponse, + ) + + async def archive( + self, + topic_id: str, + *, + section_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Archives a subscription topic and removes it from its workspace preference, + addressed by section id and topic id. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template( + "/preferences/sections/{section_id}/topics/{topic_id}", section_id=section_id, topic_id=topic_id + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def replace( + self, + topic_id: str, + *, + section_id: str, + default_status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"], + name: str, + allowed_preferences: Optional[List[Literal["snooze", "channel_preferences"]]] | Omit = omit, + description: Optional[str] | Omit = omit, + include_unsubscribe_header: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + topic_data: Optional[Dict[str, object]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceTopicGetResponse: + """Replace a topic within a workspace preference. + + Full document replacement; + missing optional fields are cleared. Same 404 rules as GET. + + Args: + default_status: The default subscription status applied when a recipient has not set their own. + + name: Human-readable name for the preference topic. + + allowed_preferences: Preference controls a recipient may customize. Omit to clear. + + description: Optional description shown under the topic on the hosted preferences page. Omit + to clear. + + include_unsubscribe_header: Whether to include a list-unsubscribe header on emails for this topic. + + routing_options: Default channels delivered for this topic. Omit to clear. + + topic_data: Arbitrary metadata associated with the topic. Omit to clear. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + if not topic_id: + raise ValueError(f"Expected a non-empty value for `topic_id` but received {topic_id!r}") + return await self._put( + path_template( + "/preferences/sections/{section_id}/topics/{topic_id}", section_id=section_id, topic_id=topic_id + ), + body=await async_maybe_transform( + { + "default_status": default_status, + "name": name, + "allowed_preferences": allowed_preferences, + "description": description, + "include_unsubscribe_header": include_unsubscribe_header, + "routing_options": routing_options, + "topic_data": topic_data, + }, + topic_replace_params.TopicReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceTopicGetResponse, + ) + + +class TopicsResourceWithRawResponse: + def __init__(self, topics: TopicsResource) -> None: + self._topics = topics + + self.create = to_raw_response_wrapper( + topics.create, + ) + self.retrieve = to_raw_response_wrapper( + topics.retrieve, + ) + self.list = to_raw_response_wrapper( + topics.list, + ) + self.archive = to_raw_response_wrapper( + topics.archive, + ) + self.replace = to_raw_response_wrapper( + topics.replace, + ) + + +class AsyncTopicsResourceWithRawResponse: + def __init__(self, topics: AsyncTopicsResource) -> None: + self._topics = topics + + self.create = async_to_raw_response_wrapper( + topics.create, + ) + self.retrieve = async_to_raw_response_wrapper( + topics.retrieve, + ) + self.list = async_to_raw_response_wrapper( + topics.list, + ) + self.archive = async_to_raw_response_wrapper( + topics.archive, + ) + self.replace = async_to_raw_response_wrapper( + topics.replace, + ) + + +class TopicsResourceWithStreamingResponse: + def __init__(self, topics: TopicsResource) -> None: + self._topics = topics + + self.create = to_streamed_response_wrapper( + topics.create, + ) + self.retrieve = to_streamed_response_wrapper( + topics.retrieve, + ) + self.list = to_streamed_response_wrapper( + topics.list, + ) + self.archive = to_streamed_response_wrapper( + topics.archive, + ) + self.replace = to_streamed_response_wrapper( + topics.replace, + ) + + +class AsyncTopicsResourceWithStreamingResponse: + def __init__(self, topics: AsyncTopicsResource) -> None: + self._topics = topics + + self.create = async_to_streamed_response_wrapper( + topics.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + topics.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + topics.list, + ) + self.archive = async_to_streamed_response_wrapper( + topics.archive, + ) + self.replace = async_to_streamed_response_wrapper( + topics.replace, + ) diff --git a/src/courier/resources/workspace_preferences/workspace_preferences.py b/src/courier/resources/workspace_preferences/workspace_preferences.py new file mode 100644 index 00000000..cdb79e2d --- /dev/null +++ b/src/courier/resources/workspace_preferences/workspace_preferences.py @@ -0,0 +1,772 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional + +import httpx + +from .topics import ( + TopicsResource, + AsyncTopicsResource, + TopicsResourceWithRawResponse, + AsyncTopicsResourceWithRawResponse, + TopicsResourceWithStreamingResponse, + AsyncTopicsResourceWithStreamingResponse, +) +from ...types import ( + workspace_preference_create_params, + workspace_preference_publish_params, + workspace_preference_replace_params, +) +from ..._types import Body, Omit, Query, Headers, NoneType, NotGiven, omit, not_given +from ..._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import ( + to_raw_response_wrapper, + to_streamed_response_wrapper, + async_to_raw_response_wrapper, + async_to_streamed_response_wrapper, +) +from ..._base_client import make_request_options +from ...types.publish_preferences_response import PublishPreferencesResponse +from ...types.shared.channel_classification import ChannelClassification +from ...types.workspace_preference_get_response import WorkspacePreferenceGetResponse +from ...types.workspace_preference_list_response import WorkspacePreferenceListResponse + +__all__ = ["WorkspacePreferencesResource", "AsyncWorkspacePreferencesResource"] + + +class WorkspacePreferencesResource(SyncAPIResource): + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + + @cached_property + def topics(self) -> TopicsResource: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + return TopicsResource(self._client) + + @cached_property + def with_raw_response(self) -> WorkspacePreferencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return WorkspacePreferencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> WorkspacePreferencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return WorkspacePreferencesResourceWithStreamingResponse(self) + + def create( + self, + *, + name: str, + description: Optional[str] | Omit = omit, + has_custom_routing: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceGetResponse: + """Creates a workspace preference and returns its generated id. + + Add subscription + topics to it afterwards with the topics endpoint. + + Args: + name: Human-readable name for the workspace preference. + + description: Optional description shown under the section on the hosted preferences page. + + has_custom_routing: Whether the workspace preference defines custom routing for its topics. + + routing_options: Default channels for the workspace preference. Defaults to empty if omitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/preferences/sections", + body=maybe_transform( + { + "name": name, + "description": description, + "has_custom_routing": has_custom_routing, + "routing_options": routing_options, + }, + workspace_preference_create_params.WorkspacePreferenceCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceGetResponse, + ) + + def retrieve( + self, + section_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceGetResponse: + """ + Returns one workspace preference by id, including its subscription topics, + routing options, and custom routing flag. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + return self._get( + path_template("/preferences/sections/{section_id}", section_id=section_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceGetResponse, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceListResponse: + """ + Returns the workspace's preferences, each embedding its subscription topics, + routing options, and whether custom routing is allowed. + """ + return self._get( + "/preferences/sections", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceListResponse, + ) + + def archive( + self, + section_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archive a workspace preference. + + The workspace preference must be empty: delete + its topics first, otherwise the request fails with 409. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/preferences/sections/{section_id}", section_id=section_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + def publish( + self, + *, + brand_id: Optional[str] | Omit = omit, + description: Optional[str] | Omit = omit, + heading: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PublishPreferencesResponse: + """ + Publishes the workspace preference page, snapshotting every preference and + topic, and returns the page id and a preview URL. + + Args: + brand_id: Brand for the hosted page - "default" (workspace default brand), "none" (no + brand), or a specific brand id. Defaults to "default". + + description: Description shown under the heading on the hosted preferences page. + + heading: Heading shown at the top of the hosted preferences page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return self._post( + "/preferences/publish", + body=maybe_transform( + { + "brand_id": brand_id, + "description": description, + "heading": heading, + }, + workspace_preference_publish_params.WorkspacePreferencePublishParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PublishPreferencesResponse, + ) + + def replace( + self, + section_id: str, + *, + name: str, + description: Optional[str] | Omit = omit, + has_custom_routing: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceGetResponse: + """Replace a workspace preference. + + Full document replacement; missing optional + fields are cleared. Topics attached to the workspace preference are unaffected. + + Args: + name: Human-readable name for the workspace preference. + + description: Optional description shown under the section on the hosted preferences page. + Omit to clear. + + has_custom_routing: Whether the workspace preference defines custom routing for its topics. + + routing_options: Default channels for the workspace preference. Omit to clear. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + return self._put( + path_template("/preferences/sections/{section_id}", section_id=section_id), + body=maybe_transform( + { + "name": name, + "description": description, + "has_custom_routing": has_custom_routing, + "routing_options": routing_options, + }, + workspace_preference_replace_params.WorkspacePreferenceReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceGetResponse, + ) + + +class AsyncWorkspacePreferencesResource(AsyncAPIResource): + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + + @cached_property + def topics(self) -> AsyncTopicsResource: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + return AsyncTopicsResource(self._client) + + @cached_property + def with_raw_response(self) -> AsyncWorkspacePreferencesResourceWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/trycourier/courier-python#accessing-raw-response-data-eg-headers + """ + return AsyncWorkspacePreferencesResourceWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncWorkspacePreferencesResourceWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/trycourier/courier-python#with_streaming_response + """ + return AsyncWorkspacePreferencesResourceWithStreamingResponse(self) + + async def create( + self, + *, + name: str, + description: Optional[str] | Omit = omit, + has_custom_routing: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceGetResponse: + """Creates a workspace preference and returns its generated id. + + Add subscription + topics to it afterwards with the topics endpoint. + + Args: + name: Human-readable name for the workspace preference. + + description: Optional description shown under the section on the hosted preferences page. + + has_custom_routing: Whether the workspace preference defines custom routing for its topics. + + routing_options: Default channels for the workspace preference. Defaults to empty if omitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/preferences/sections", + body=await async_maybe_transform( + { + "name": name, + "description": description, + "has_custom_routing": has_custom_routing, + "routing_options": routing_options, + }, + workspace_preference_create_params.WorkspacePreferenceCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceGetResponse, + ) + + async def retrieve( + self, + section_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceGetResponse: + """ + Returns one workspace preference by id, including its subscription topics, + routing options, and custom routing flag. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + return await self._get( + path_template("/preferences/sections/{section_id}", section_id=section_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceGetResponse, + ) + + async def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceListResponse: + """ + Returns the workspace's preferences, each embedding its subscription topics, + routing options, and whether custom routing is allowed. + """ + return await self._get( + "/preferences/sections", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceListResponse, + ) + + async def archive( + self, + section_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """Archive a workspace preference. + + The workspace preference must be empty: delete + its topics first, otherwise the request fails with 409. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/preferences/sections/{section_id}", section_id=section_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + async def publish( + self, + *, + brand_id: Optional[str] | Omit = omit, + description: Optional[str] | Omit = omit, + heading: Optional[str] | Omit = omit, + idempotency_key: str | Omit = omit, + x_idempotency_expiration: str | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> PublishPreferencesResponse: + """ + Publishes the workspace preference page, snapshotting every preference and + topic, and returns the page id and a preview URL. + + Args: + brand_id: Brand for the hosted page - "default" (workspace default brand), "none" (no + brand), or a specific brand id. Defaults to "default". + + description: Description shown under the heading on the hosted preferences page. + + heading: Heading shown at the top of the hosted preferences page. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = { + **strip_not_given( + { + "Idempotency-Key": idempotency_key, + "x-idempotency-expiration": x_idempotency_expiration, + } + ), + **(extra_headers or {}), + } + return await self._post( + "/preferences/publish", + body=await async_maybe_transform( + { + "brand_id": brand_id, + "description": description, + "heading": heading, + }, + workspace_preference_publish_params.WorkspacePreferencePublishParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PublishPreferencesResponse, + ) + + async def replace( + self, + section_id: str, + *, + name: str, + description: Optional[str] | Omit = omit, + has_custom_routing: Optional[bool] | Omit = omit, + routing_options: Optional[List[ChannelClassification]] | Omit = omit, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> WorkspacePreferenceGetResponse: + """Replace a workspace preference. + + Full document replacement; missing optional + fields are cleared. Topics attached to the workspace preference are unaffected. + + Args: + name: Human-readable name for the workspace preference. + + description: Optional description shown under the section on the hosted preferences page. + Omit to clear. + + has_custom_routing: Whether the workspace preference defines custom routing for its topics. + + routing_options: Default channels for the workspace preference. Omit to clear. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not section_id: + raise ValueError(f"Expected a non-empty value for `section_id` but received {section_id!r}") + return await self._put( + path_template("/preferences/sections/{section_id}", section_id=section_id), + body=await async_maybe_transform( + { + "name": name, + "description": description, + "has_custom_routing": has_custom_routing, + "routing_options": routing_options, + }, + workspace_preference_replace_params.WorkspacePreferenceReplaceParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=WorkspacePreferenceGetResponse, + ) + + +class WorkspacePreferencesResourceWithRawResponse: + def __init__(self, workspace_preferences: WorkspacePreferencesResource) -> None: + self._workspace_preferences = workspace_preferences + + self.create = to_raw_response_wrapper( + workspace_preferences.create, + ) + self.retrieve = to_raw_response_wrapper( + workspace_preferences.retrieve, + ) + self.list = to_raw_response_wrapper( + workspace_preferences.list, + ) + self.archive = to_raw_response_wrapper( + workspace_preferences.archive, + ) + self.publish = to_raw_response_wrapper( + workspace_preferences.publish, + ) + self.replace = to_raw_response_wrapper( + workspace_preferences.replace, + ) + + @cached_property + def topics(self) -> TopicsResourceWithRawResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + return TopicsResourceWithRawResponse(self._workspace_preferences.topics) + + +class AsyncWorkspacePreferencesResourceWithRawResponse: + def __init__(self, workspace_preferences: AsyncWorkspacePreferencesResource) -> None: + self._workspace_preferences = workspace_preferences + + self.create = async_to_raw_response_wrapper( + workspace_preferences.create, + ) + self.retrieve = async_to_raw_response_wrapper( + workspace_preferences.retrieve, + ) + self.list = async_to_raw_response_wrapper( + workspace_preferences.list, + ) + self.archive = async_to_raw_response_wrapper( + workspace_preferences.archive, + ) + self.publish = async_to_raw_response_wrapper( + workspace_preferences.publish, + ) + self.replace = async_to_raw_response_wrapper( + workspace_preferences.replace, + ) + + @cached_property + def topics(self) -> AsyncTopicsResourceWithRawResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + return AsyncTopicsResourceWithRawResponse(self._workspace_preferences.topics) + + +class WorkspacePreferencesResourceWithStreamingResponse: + def __init__(self, workspace_preferences: WorkspacePreferencesResource) -> None: + self._workspace_preferences = workspace_preferences + + self.create = to_streamed_response_wrapper( + workspace_preferences.create, + ) + self.retrieve = to_streamed_response_wrapper( + workspace_preferences.retrieve, + ) + self.list = to_streamed_response_wrapper( + workspace_preferences.list, + ) + self.archive = to_streamed_response_wrapper( + workspace_preferences.archive, + ) + self.publish = to_streamed_response_wrapper( + workspace_preferences.publish, + ) + self.replace = to_streamed_response_wrapper( + workspace_preferences.replace, + ) + + @cached_property + def topics(self) -> TopicsResourceWithStreamingResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + return TopicsResourceWithStreamingResponse(self._workspace_preferences.topics) + + +class AsyncWorkspacePreferencesResourceWithStreamingResponse: + def __init__(self, workspace_preferences: AsyncWorkspacePreferencesResource) -> None: + self._workspace_preferences = workspace_preferences + + self.create = async_to_streamed_response_wrapper( + workspace_preferences.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + workspace_preferences.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + workspace_preferences.list, + ) + self.archive = async_to_streamed_response_wrapper( + workspace_preferences.archive, + ) + self.publish = async_to_streamed_response_wrapper( + workspace_preferences.publish, + ) + self.replace = async_to_streamed_response_wrapper( + workspace_preferences.replace, + ) + + @cached_property + def topics(self) -> AsyncTopicsResourceWithStreamingResponse: + """ + Manage the workspace catalog of subscription topics, the sections that group them, and publishing the preference page. + """ + return AsyncTopicsResourceWithStreamingResponse(self._workspace_preferences.topics) diff --git a/src/courier/types/__init__.py b/src/courier/types/__init__.py new file mode 100644 index 00000000..c4b44aa7 --- /dev/null +++ b/src/courier/types/__init__.py @@ -0,0 +1,353 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from . import ( + shared, + tenants, + audience, + journey_response, + audience_list_response, + element_with_checksums, + audience_update_response, + notification_list_response, + routing_strategy_get_response, + notification_content_get_response, +) +from .. import _compat +from .logo import Logo as Logo +from .brand import Brand as Brand +from .check import Check as Check +from .icons import Icons as Icons +from .shared import ( + Utm as Utm, + Expo as Expo, + Rule as Rule, + Slack as Slack, + Token as Token, + Paging as Paging, + Channel as Channel, + Discord as Discord, + MsTeams as MsTeams, + Intercom as Intercom, + Metadata as Metadata, + Timeouts as Timeouts, + Alignment as Alignment, + Pagerduty as Pagerduty, + TextStyle as TextStyle, + DeviceType as DeviceType, + ListFilter as ListFilter, + Preference as Preference, + UserProfile as UserProfile, + FilterConfig as FilterConfig, + ElementalNode as ElementalNode, + ListRecipient as ListRecipient, + SendToChannel as SendToChannel, + UserRecipient as UserRecipient, + WebhookMethod as WebhookMethod, + AirshipProfile as AirshipProfile, + AudienceFilter as AudienceFilter, + MessageContext as MessageContext, + MessageRouting as MessageRouting, + MultipleTokens as MultipleTokens, + SlackRecipient as SlackRecipient, + WebhookProfile as WebhookProfile, + ChannelMetadata as ChannelMetadata, + MessageChannels as MessageChannels, + WebhookAuthMode as WebhookAuthMode, + ElementalContent as ElementalContent, + MessageProviders as MessageProviders, + MsTeamsRecipient as MsTeamsRecipient, + PreferenceStatus as PreferenceStatus, + SendToSlackEmail as SendToSlackEmail, + WebhookRecipient as WebhookRecipient, + AudienceRecipient as AudienceRecipient, + ChannelPreference as ChannelPreference, + ElementalBaseNode as ElementalBaseNode, + IntercomRecipient as IntercomRecipient, + SendDirectMessage as SendDirectMessage, + SendToSlackUserID as SendToSlackUserID, + PagerdutyRecipient as PagerdutyRecipient, + SendToMsTeamsEmail as SendToMsTeamsEmail, + SendToSlackChannel as SendToSlackChannel, + WebhookProfileType as WebhookProfileType, + SendToMsTeamsUserID as SendToMsTeamsUserID, + SlackBaseProperties as SlackBaseProperties, + AudienceFilterConfig as AudienceFilterConfig, + ElementalChannelNode as ElementalChannelNode, + ListPatternRecipient as ListPatternRecipient, + MessageProvidersType as MessageProvidersType, + RecipientPreferences as RecipientPreferences, + ChannelClassification as ChannelClassification, + ElementalContentSugar as ElementalContentSugar, + MessageRoutingChannel as MessageRoutingChannel, + MsTeamsBaseProperties as MsTeamsBaseProperties, + WebhookAuthentication as WebhookAuthentication, + AirshipProfileAudience as AirshipProfileAudience, + SendToMsTeamsChannelID as SendToMsTeamsChannelID, + SendToMsTeamsChannelName as SendToMsTeamsChannelName, + UserProfileFirebaseToken as UserProfileFirebaseToken, + ElementalHTMLNodeWithType as ElementalHTMLNodeWithType, + ElementalMetaNodeWithType as ElementalMetaNodeWithType, + ElementalTextNodeWithType as ElementalTextNodeWithType, + ElementalImageNodeWithType as ElementalImageNodeWithType, + ElementalQuoteNodeWithType as ElementalQuoteNodeWithType, + ElementalActionNodeWithType as ElementalActionNodeWithType, + SendToMsTeamsConversationID as SendToMsTeamsConversationID, + ElementalChannelNodeWithType as ElementalChannelNodeWithType, + ElementalDividerNodeWithType as ElementalDividerNodeWithType, + NotificationPreferenceDetails as NotificationPreferenceDetails, +) +from .tenant import Tenant as Tenant +from .journey import Journey as Journey +from .audience import Audience as Audience +from .provider import Provider as Provider +from .broadcast import Broadcast as Broadcast +from .base_check import BaseCheck as BaseCheck +from .email_head import EmailHead as EmailHead +from .logo_param import LogoParam as LogoParam +from .audit_event import AuditEvent as AuditEvent +from .icons_param import IconsParam as IconsParam +from .brand_colors import BrandColors as BrandColors +from .email_footer import EmailFooter as EmailFooter +from .email_header import EmailHeader as EmailHeader +from .journey_node import JourneyNode as JourneyNode +from .version_node import VersionNode as VersionNode +from .brand_snippet import BrandSnippet as BrandSnippet +from .journey_state import JourneyState as JourneyState +from .brand_settings import BrandSettings as BrandSettings +from .brand_snippets import BrandSnippets as BrandSnippets +from .brand_template import BrandTemplate as BrandTemplate +from .digest_category import DigestCategory as DigestCategory +from .digest_instance import DigestInstance as DigestInstance +from .journey_ai_node import JourneyAINode as JourneyAINode +from .message_details import MessageDetails as MessageDetails +from .base_check_param import BaseCheckParam as BaseCheckParam +from .email_head_param import EmailHeadParam as EmailHeadParam +from .journey_response import JourneyResponse as JourneyResponse +from .list_list_params import ListListParams as ListListParams +from .brand_list_params import BrandListParams as BrandListParams +from .journey_exit_node import JourneyExitNode as JourneyExitNode +from .journey_send_node import JourneySendNode as JourneySendNode +from .subscription_list import SubscriptionList as SubscriptionList +from .widget_background import WidgetBackground as WidgetBackground +from .brand_colors_param import BrandColorsParam as BrandColorsParam +from .broadcast_schedule import BroadcastSchedule as BroadcastSchedule +from .email_footer_param import EmailFooterParam as EmailFooterParam +from .email_header_param import EmailHeaderParam as EmailHeaderParam +from .journey_experiment import JourneyExperiment as JourneyExperiment +from .journey_node_param import JourneyNodeParam as JourneyNodeParam +from .list_list_response import ListListResponse as ListListResponse +from .list_update_params import ListUpdateParams as ListUpdateParams +from .tenant_association import TenantAssociation as TenantAssociation +from .tenant_list_params import TenantListParams as TenantListParams +from .automation_template import AutomationTemplate as AutomationTemplate +from .brand_create_params import BrandCreateParams as BrandCreateParams +from .brand_list_response import BrandListResponse as BrandListResponse +from .brand_snippet_param import BrandSnippetParam as BrandSnippetParam +from .brand_update_params import BrandUpdateParams as BrandUpdateParams +from .default_preferences import DefaultPreferences as DefaultPreferences +from .journey_list_params import JourneyListParams as JourneyListParams +from .message_list_params import MessageListParams as MessageListParams +from .send_message_params import SendMessageParams as SendMessageParams +from .audience_list_params import AudienceListParams as AudienceListParams +from .brand_settings_email import BrandSettingsEmail as BrandSettingsEmail +from .brand_settings_param import BrandSettingsParam as BrandSettingsParam +from .brand_snippets_param import BrandSnippetsParam as BrandSnippetsParam +from .brand_template_param import BrandTemplateParam as BrandTemplateParam +from .journey_version_item import JourneyVersionItem as JourneyVersionItem +from .provider_list_params import ProviderListParams as ProviderListParams +from .tenant_list_response import TenantListResponse as TenantListResponse +from .tenant_update_params import TenantUpdateParams as TenantUpdateParams +from .brand_settings_in_app import BrandSettingsInApp as BrandSettingsInApp +from .broadcast_list_params import BroadcastListParams as BroadcastListParams +from .broadcast_send_params import BroadcastSendParams as BroadcastSendParams +from .journey_ai_node_param import JourneyAINodeParam as JourneyAINodeParam +from .journey_cancel_params import JourneyCancelParams as JourneyCancelParams +from .journey_create_params import JourneyCreateParams as JourneyCreateParams +from .journey_invoke_params import JourneyInvokeParams as JourneyInvokeParams +from .message_list_response import MessageListResponse as MessageListResponse +from .profile_create_params import ProfileCreateParams as ProfileCreateParams +from .profile_update_params import ProfileUpdateParams as ProfileUpdateParams +from .send_message_response import SendMessageResponse as SendMessageResponse +from .audience_list_response import AudienceListResponse as AudienceListResponse +from .audience_update_params import AudienceUpdateParams as AudienceUpdateParams +from .automation_list_params import AutomationListParams as AutomationListParams +from .element_with_checksums import ElementWithChecksums as ElementWithChecksums +from .journey_condition_atom import JourneyConditionAtom as JourneyConditionAtom +from .journey_merge_strategy import JourneyMergeStrategy as JourneyMergeStrategy +from .journey_publish_params import JourneyPublishParams as JourneyPublishParams +from .journey_replace_params import JourneyReplaceParams as JourneyReplaceParams +from .journeys_list_response import JourneysListResponse as JourneysListResponse +from .message_history_params import MessageHistoryParams as MessageHistoryParams +from .profile_replace_params import ProfileReplaceParams as ProfileReplaceParams +from .provider_create_params import ProviderCreateParams as ProviderCreateParams +from .provider_list_response import ProviderListResponse as ProviderListResponse +from .provider_update_params import ProviderUpdateParams as ProviderUpdateParams +from .subscription_topic_new import SubscriptionTopicNew as SubscriptionTopicNew +from .audit_event_list_params import AuditEventListParams as AuditEventListParams +from .auth_issue_token_params import AuthIssueTokenParams as AuthIssueTokenParams +from .broadcast_create_params import BroadcastCreateParams as BroadcastCreateParams +from .broadcast_list_response import BroadcastListResponse as BroadcastListResponse +from .broadcast_update_params import BroadcastUpdateParams as BroadcastUpdateParams +from .cancel_journey_response import CancelJourneyResponse as CancelJourneyResponse +from .journey_condition_group import JourneyConditionGroup as JourneyConditionGroup +from .journey_exit_node_param import JourneyExitNodeParam as JourneyExitNodeParam +from .journey_retrieve_params import JourneyRetrieveParams as JourneyRetrieveParams +from .journey_send_node_param import JourneySendNodeParam as JourneySendNodeParam +from .message_resend_response import MessageResendResponse as MessageResendResponse +from .profile_create_response import ProfileCreateResponse as ProfileCreateResponse +from .providers_catalog_entry import ProvidersCatalogEntry as ProvidersCatalogEntry +from .widget_background_param import WidgetBackgroundParam as WidgetBackgroundParam +from .audience_update_response import AudienceUpdateResponse as AudienceUpdateResponse +from .journey_conditions_field import JourneyConditionsField as JourneyConditionsField +from .journey_delay_until_node import JourneyDelayUntilNode as JourneyDelayUntilNode +from .journey_experiment_param import JourneyExperimentParam as JourneyExperimentParam +from .journey_template_summary import JourneyTemplateSummary as JourneyTemplateSummary +from .journeys_invoke_response import JourneysInvokeResponse as JourneysInvokeResponse +from .message_content_response import MessageContentResponse as MessageContentResponse +from .message_history_response import MessageHistoryResponse as MessageHistoryResponse +from .notification_get_content import NotificationGetContent as NotificationGetContent +from .notification_list_params import NotificationListParams as NotificationListParams +from .profile_replace_response import ProfileReplaceResponse as ProfileReplaceResponse +from .routing_strategy_summary import RoutingStrategySummary as RoutingStrategySummary +from .tenant_association_param import TenantAssociationParam as TenantAssociationParam +from .tenant_list_users_params import TenantListUsersParams as TenantListUsersParams +from .audit_event_list_response import AuditEventListResponse as AuditEventListResponse +from .auth_issue_token_response import AuthIssueTokenResponse as AuthIssueTokenResponse +from .broadcast_schedule_params import BroadcastScheduleParams as BroadcastScheduleParams +from .default_preferences_param import DefaultPreferencesParam as DefaultPreferencesParam +from .message_retrieve_response import MessageRetrieveResponse as MessageRetrieveResponse +from .profile_retrieve_response import ProfileRetrieveResponse as ProfileRetrieveResponse +from .translation_update_params import TranslationUpdateParams as TranslationUpdateParams +from .automation_invoke_response import AutomationInvokeResponse as AutomationInvokeResponse +from .brand_settings_email_param import BrandSettingsEmailParam as BrandSettingsEmailParam +from .inbound_track_event_params import InboundTrackEventParams as InboundTrackEventParams +from .journey_experiment_variant import JourneyExperimentVariant as JourneyExperimentVariant +from .notification_create_params import NotificationCreateParams as NotificationCreateParams +from .notification_list_response import NotificationListResponse as NotificationListResponse +from .tenant_list_users_response import TenantListUsersResponse as TenantListUsersResponse +from .brand_settings_in_app_param import BrandSettingsInAppParam as BrandSettingsInAppParam +from .journey_delay_duration_node import JourneyDelayDurationNode as JourneyDelayDurationNode +from .journey_fetch_post_put_node import JourneyFetchPostPutNode as JourneyFetchPostPutNode +from .notification_publish_params import NotificationPublishParams as NotificationPublishParams +from .notification_replace_params import NotificationReplaceParams as NotificationReplaceParams +from .notification_template_alias import NotificationTemplateAlias as NotificationTemplateAlias +from .notification_template_state import NotificationTemplateState as NotificationTemplateState +from .tenant_template_input_param import TenantTemplateInputParam as TenantTemplateInputParam +from .audience_list_members_params import AudienceListMembersParams as AudienceListMembersParams +from .broadcast_put_content_params import BroadcastPutContentParams as BroadcastPutContentParams +from .cancel_journey_request_param import CancelJourneyRequestParam as CancelJourneyRequestParam +from .inbound_track_event_response import InboundTrackEventResponse as InboundTrackEventResponse +from .journey_condition_atom_param import JourneyConditionAtomParam as JourneyConditionAtomParam +from .journey_segment_trigger_node import JourneySegmentTriggerNode as JourneySegmentTriggerNode +from .journey_throttle_static_node import JourneyThrottleStaticNode as JourneyThrottleStaticNode +from .notification_retrieve_params import NotificationRetrieveParams as NotificationRetrieveParams +from .publish_preferences_response import PublishPreferencesResponse as PublishPreferencesResponse +from .put_tenant_template_response import PutTenantTemplateResponse as PutTenantTemplateResponse +from .routing_strategy_list_params import RoutingStrategyListParams as RoutingStrategyListParams +from .subscription_topic_new_param import SubscriptionTopicNewParam as SubscriptionTopicNewParam +from .digest_instance_list_response import DigestInstanceListResponse as DigestInstanceListResponse +from .journey_condition_group_param import JourneyConditionGroupParam as JourneyConditionGroupParam +from .journey_fetch_get_delete_node import JourneyFetchGetDeleteNode as JourneyFetchGetDeleteNode +from .journey_template_get_response import JourneyTemplateGetResponse as JourneyTemplateGetResponse +from .journey_throttle_dynamic_node import JourneyThrottleDynamicNode as JourneyThrottleDynamicNode +from .notification_template_payload import NotificationTemplatePayload as NotificationTemplatePayload +from .notification_template_summary import NotificationTemplateSummary as NotificationTemplateSummary +from .routing_strategy_get_response import RoutingStrategyGetResponse as RoutingStrategyGetResponse +from .translation_retrieve_response import TranslationRetrieveResponse as TranslationRetrieveResponse +from .audience_list_members_response import AudienceListMembersResponse as AudienceListMembersResponse +from .journey_condition_nested_group import JourneyConditionNestedGroup as JourneyConditionNestedGroup +from .journey_conditions_field_param import JourneyConditionsFieldParam as JourneyConditionsFieldParam +from .journey_delay_until_node_param import JourneyDelayUntilNodeParam as JourneyDelayUntilNodeParam +from .journey_template_list_response import JourneyTemplateListResponse as JourneyTemplateListResponse +from .journey_versions_list_response import JourneyVersionsListResponse as JourneyVersionsListResponse +from .notification_put_locale_params import NotificationPutLocaleParams as NotificationPutLocaleParams +from .notification_template_response import NotificationTemplateResponse as NotificationTemplateResponse +from .routing_strategy_create_params import RoutingStrategyCreateParams as RoutingStrategyCreateParams +from .routing_strategy_list_response import RoutingStrategyListResponse as RoutingStrategyListResponse +from .journey_api_invoke_trigger_node import JourneyAPIInvokeTriggerNode as JourneyAPIInvokeTriggerNode +from .notification_put_content_params import NotificationPutContentParams as NotificationPutContentParams +from .notification_put_element_params import NotificationPutElementParams as NotificationPutElementParams +from .routing_strategy_replace_params import RoutingStrategyReplaceParams as RoutingStrategyReplaceParams +from .base_template_tenant_association import BaseTemplateTenantAssociation as BaseTemplateTenantAssociation +from .journey_experiment_variant_param import JourneyExperimentVariantParam as JourneyExperimentVariantParam +from .automation_template_list_response import AutomationTemplateListResponse as AutomationTemplateListResponse +from .broadcast_retrieve_content_params import BroadcastRetrieveContentParams as BroadcastRetrieveContentParams +from .journey_delay_duration_node_param import JourneyDelayDurationNodeParam as JourneyDelayDurationNodeParam +from .journey_fetch_post_put_node_param import JourneyFetchPostPutNodeParam as JourneyFetchPostPutNodeParam +from .notification_content_get_response import NotificationContentGetResponse as NotificationContentGetResponse +from .notification_list_versions_params import NotificationListVersionsParams as NotificationListVersionsParams +from .put_subscriptions_recipient_param import PutSubscriptionsRecipientParam as PutSubscriptionsRecipientParam +from .workspace_preference_get_response import WorkspacePreferenceGetResponse as WorkspacePreferenceGetResponse +from .journey_segment_trigger_node_param import JourneySegmentTriggerNodeParam as JourneySegmentTriggerNodeParam +from .journey_throttle_static_node_param import JourneyThrottleStaticNodeParam as JourneyThrottleStaticNodeParam +from .workspace_preference_create_params import WorkspacePreferenceCreateParams as WorkspacePreferenceCreateParams +from .workspace_preference_list_response import WorkspacePreferenceListResponse as WorkspacePreferenceListResponse +from .journey_fetch_get_delete_node_param import JourneyFetchGetDeleteNodeParam as JourneyFetchGetDeleteNodeParam +from .journey_throttle_dynamic_node_param import JourneyThrottleDynamicNodeParam as JourneyThrottleDynamicNodeParam +from .notification_template_payload_param import NotificationTemplatePayloadParam as NotificationTemplatePayloadParam +from .workspace_preference_publish_params import WorkspacePreferencePublishParams as WorkspacePreferencePublishParams +from .workspace_preference_replace_params import WorkspacePreferenceReplaceParams as WorkspacePreferenceReplaceParams +from .journey_condition_nested_group_param import JourneyConditionNestedGroupParam as JourneyConditionNestedGroupParam +from .notification_retrieve_content_params import NotificationRetrieveContentParams as NotificationRetrieveContentParams +from .associated_notification_list_response import ( + AssociatedNotificationListResponse as AssociatedNotificationListResponse, +) +from .journey_api_invoke_trigger_node_param import JourneyAPIInvokeTriggerNodeParam as JourneyAPIInvokeTriggerNodeParam +from .post_tenant_template_publish_response import ( + PostTenantTemplatePublishResponse as PostTenantTemplatePublishResponse, +) +from .subscribe_to_lists_request_item_param import SubscribeToListsRequestItemParam as SubscribeToListsRequestItemParam +from .notification_content_mutation_response import ( + NotificationContentMutationResponse as NotificationContentMutationResponse, +) +from .notification_retrieve_content_response import ( + NotificationRetrieveContentResponse as NotificationRetrieveContentResponse, +) +from .workspace_preference_topic_get_response import ( + WorkspacePreferenceTopicGetResponse as WorkspacePreferenceTopicGetResponse, +) +from .workspace_preference_topic_list_response import ( + WorkspacePreferenceTopicListResponse as WorkspacePreferenceTopicListResponse, +) +from .notification_template_write_payload_param import ( + NotificationTemplateWritePayloadParam as NotificationTemplateWritePayloadParam, +) +from .routing_strategy_list_notifications_params import ( + RoutingStrategyListNotificationsParams as RoutingStrategyListNotificationsParams, +) +from .notification_template_version_list_response import ( + NotificationTemplateVersionListResponse as NotificationTemplateVersionListResponse, +) + +# Rebuild cyclical models only after all modules are imported. +# This ensures that, when building the deferred (due to cyclical references) model schema, +# Pydantic can resolve the necessary references. +# See: https://github.com/pydantic/pydantic/issues/11250 for more context. +if _compat.PYDANTIC_V1: + audience.Audience.update_forward_refs() # type: ignore + audience_update_response.AudienceUpdateResponse.update_forward_refs() # type: ignore + audience_list_response.AudienceListResponse.update_forward_refs() # type: ignore + journey_response.JourneyResponse.update_forward_refs() # type: ignore + element_with_checksums.ElementWithChecksums.update_forward_refs() # type: ignore + notification_content_get_response.NotificationContentGetResponse.update_forward_refs() # type: ignore + notification_list_response.NotificationListResponse.update_forward_refs() # type: ignore + routing_strategy_get_response.RoutingStrategyGetResponse.update_forward_refs() # type: ignore + tenants.template_list_response.TemplateListResponse.update_forward_refs() # type: ignore + shared.audience_filter_config.AudienceFilterConfig.update_forward_refs() # type: ignore + shared.filter_config.FilterConfig.update_forward_refs() # type: ignore + shared.message_routing.MessageRouting.update_forward_refs() # type: ignore +else: + audience.Audience.model_rebuild(_parent_namespace_depth=0) + audience_update_response.AudienceUpdateResponse.model_rebuild(_parent_namespace_depth=0) + audience_list_response.AudienceListResponse.model_rebuild(_parent_namespace_depth=0) + journey_response.JourneyResponse.model_rebuild(_parent_namespace_depth=0) + element_with_checksums.ElementWithChecksums.model_rebuild(_parent_namespace_depth=0) + notification_content_get_response.NotificationContentGetResponse.model_rebuild(_parent_namespace_depth=0) + notification_list_response.NotificationListResponse.model_rebuild(_parent_namespace_depth=0) + routing_strategy_get_response.RoutingStrategyGetResponse.model_rebuild(_parent_namespace_depth=0) + tenants.template_list_response.TemplateListResponse.model_rebuild(_parent_namespace_depth=0) + shared.audience_filter_config.AudienceFilterConfig.model_rebuild(_parent_namespace_depth=0) + shared.filter_config.FilterConfig.model_rebuild(_parent_namespace_depth=0) + shared.message_routing.MessageRouting.model_rebuild(_parent_namespace_depth=0) diff --git a/src/courier/types/associated_notification_list_response.py b/src/courier/types/associated_notification_list_response.py new file mode 100644 index 00000000..475d9e2e --- /dev/null +++ b/src/courier/types/associated_notification_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging +from .notification_template_summary import NotificationTemplateSummary + +__all__ = ["AssociatedNotificationListResponse"] + + +class AssociatedNotificationListResponse(BaseModel): + """Paginated list of notification templates associated with a routing strategy.""" + + paging: Paging + + results: List[NotificationTemplateSummary] diff --git a/src/courier/types/audience.py b/src/courier/types/audience.py new file mode 100644 index 00000000..e3b1bce0 --- /dev/null +++ b/src/courier/types/audience.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["Audience"] + + +class Audience(BaseModel): + id: str + """A unique identifier representing the audience_id""" + + created_at: str + + description: str + """A description of the audience""" + + name: str + """The name of the audience""" + + updated_at: str + + filter: Optional["AudienceFilterConfig"] = None + """ + Filter configuration for audience membership containing an array of filter rules + """ + + operator: Optional[Literal["AND", "OR"]] = None + """The logical operator (AND/OR) combining the top-level `filter.filters`. + + Convenience alias for `filter.operator`. + """ + + +from .shared.audience_filter_config import AudienceFilterConfig diff --git a/src/courier/types/audience_list_members_params.py b/src/courier/types/audience_list_members_params.py new file mode 100644 index 00000000..31b54efb --- /dev/null +++ b/src/courier/types/audience_list_members_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["AudienceListMembersParams"] + + +class AudienceListMembersParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of members""" diff --git a/src/courier/types/audience_list_members_response.py b/src/courier/types/audience_list_members_response.py new file mode 100644 index 00000000..cdf117c7 --- /dev/null +++ b/src/courier/types/audience_list_members_response.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging + +__all__ = ["AudienceListMembersResponse", "Item"] + + +class Item(BaseModel): + added_at: str + + audience_id: str + + audience_version: int + + member_id: str + + reason: str + + +class AudienceListMembersResponse(BaseModel): + items: List[Item] + + paging: Paging diff --git a/src/courier/types/audience_list_params.py b/src/courier/types/audience_list_params.py new file mode 100644 index 00000000..32f8aa63 --- /dev/null +++ b/src/courier/types/audience_list_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["AudienceListParams"] + + +class AudienceListParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of audiences""" diff --git a/src/courier/types/audience_list_response.py b/src/courier/types/audience_list_response.py new file mode 100644 index 00000000..336ba501 --- /dev/null +++ b/src/courier/types/audience_list_response.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging + +__all__ = ["AudienceListResponse"] + + +class AudienceListResponse(BaseModel): + items: List["Audience"] + + paging: Paging + + +from .audience import Audience diff --git a/src/courier/types/audience_update_params.py b/src/courier/types/audience_update_params.py new file mode 100644 index 00000000..fd9ccc4a --- /dev/null +++ b/src/courier/types/audience_update_params.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, TypedDict + +__all__ = ["AudienceUpdateParams"] + + +class AudienceUpdateParams(TypedDict, total=False): + description: Optional[str] + """A description of the audience""" + + filter: Optional["AudienceFilterConfig"] + """ + Filter configuration for audience membership containing an array of filter rules + """ + + name: Optional[str] + """The name of the audience""" + + operator: Optional[Literal["AND", "OR"]] + """The logical operator (AND/OR) combining the top-level `filter.filters`. + + Convenience alias for `filter.operator`: if set, it is applied to the top-level + filter group. Prefer setting `operator` directly inside `filter`. + """ + + +from .shared_params.audience_filter_config import AudienceFilterConfig diff --git a/src/courier/types/audience_update_response.py b/src/courier/types/audience_update_response.py new file mode 100644 index 00000000..2f0f427a --- /dev/null +++ b/src/courier/types/audience_update_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .._models import BaseModel + +__all__ = ["AudienceUpdateResponse"] + + +class AudienceUpdateResponse(BaseModel): + audience: "Audience" + + +from .audience import Audience diff --git a/src/courier/types/audit_event.py b/src/courier/types/audit_event.py new file mode 100644 index 00000000..7e00c7e8 --- /dev/null +++ b/src/courier/types/audit_event.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["AuditEvent", "Actor"] + + +class Actor(BaseModel): + id: str + + email: Optional[str] = None + + +class AuditEvent(BaseModel): + actor: Actor + + audit_event_id: str = FieldInfo(alias="auditEventId") + + source: str + + target: str + + timestamp: str + + type: str diff --git a/src/courier/types/audit_event_list_params.py b/src/courier/types/audit_event_list_params.py new file mode 100644 index 00000000..8eb591a8 --- /dev/null +++ b/src/courier/types/audit_event_list_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["AuditEventListParams"] + + +class AuditEventListParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of audit events.""" diff --git a/src/courier/types/audit_event_list_response.py b/src/courier/types/audit_event_list_response.py new file mode 100644 index 00000000..7b3f3276 --- /dev/null +++ b/src/courier/types/audit_event_list_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .audit_event import AuditEvent +from .shared.paging import Paging + +__all__ = ["AuditEventListResponse"] + + +class AuditEventListResponse(BaseModel): + paging: Paging + + results: List[AuditEvent] diff --git a/src/courier/types/auth_issue_token_params.py b/src/courier/types/auth_issue_token_params.py new file mode 100644 index 00000000..73cd7a7f --- /dev/null +++ b/src/courier/types/auth_issue_token_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["AuthIssueTokenParams"] + + +class AuthIssueTokenParams(TypedDict, total=False): + expires_in: Required[str] + """Duration for token expiration. Accepts various time formats: + + - "2 hours" - 2 hours from now + - "1d" - 1 day + - "3 days" - 3 days + - "10h" - 10 hours + - "2.5 hrs" - 2.5 hours + - "1m" - 1 minute + - "5s" - 5 seconds + - "1y" - 1 year + """ + + scope: Required[str] + """Available scopes: + + - `user_id:` - Defines which user the token will be scoped to. Multiple + can be listed if needed. Ex `user_id:pigeon user_id:bluebird`. + - `read:messages` - Read messages. + - `read:user-tokens` - Read user push tokens. + - `write:user-tokens` - Write user push tokens. + - `read:brands[:]` - Read brands, optionally restricted to a specific + brand_id. Examples `read:brands`, `read:brands:my_brand`. + - `write:brands[:]` - Write brands, optionally restricted to a + specific brand_id. Examples `write:brands`, `write:brands:my_brand`. + - `inbox:read:messages` - Read inbox messages. + - `inbox:write:events` - Write inbox events, such as mark message as read. + - `read:preferences` - Read user preferences. + - `write:preferences` - Write user preferences. Example: + `user_id:user123 write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands` + """ diff --git a/src/courier/types/auth_issue_token_response.py b/src/courier/types/auth_issue_token_response.py new file mode 100644 index 00000000..8d0583f3 --- /dev/null +++ b/src/courier/types/auth_issue_token_response.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["AuthIssueTokenResponse"] + + +class AuthIssueTokenResponse(BaseModel): + token: str diff --git a/src/courier/types/automation_invoke_response.py b/src/courier/types/automation_invoke_response.py new file mode 100644 index 00000000..ecd89ed8 --- /dev/null +++ b/src/courier/types/automation_invoke_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["AutomationInvokeResponse"] + + +class AutomationInvokeResponse(BaseModel): + run_id: str = FieldInfo(alias="runId") diff --git a/src/courier/types/automation_list_params.py b/src/courier/types/automation_list_params.py new file mode 100644 index 00000000..d7ab99d6 --- /dev/null +++ b/src/courier/types/automation_list_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["AutomationListParams"] + + +class AutomationListParams(TypedDict, total=False): + cursor: str + """A cursor token for pagination. + + Use the cursor from the previous response to fetch the next page of results. + """ + + version: Literal["published", "draft"] + """The version of templates to retrieve. + + Accepted values are published (for published templates) or draft (for draft + templates). Defaults to published. + """ diff --git a/src/courier/types/automation_template.py b/src/courier/types/automation_template.py new file mode 100644 index 00000000..9851467e --- /dev/null +++ b/src/courier/types/automation_template.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["AutomationTemplate"] + + +class AutomationTemplate(BaseModel): + id: str + """The unique identifier of the automation template.""" + + name: str + """The name of the automation template.""" + + version: Literal["published", "draft"] + """The version of the template published or drafted.""" + + created_at: Optional[datetime] = FieldInfo(alias="createdAt", default=None) + """ISO 8601 timestamp when the template was created.""" + + updated_at: Optional[datetime] = FieldInfo(alias="updatedAt", default=None) + """ISO 8601 timestamp when the template was last updated.""" diff --git a/src/courier/types/automation_template_list_response.py b/src/courier/types/automation_template_list_response.py new file mode 100644 index 00000000..80cfd7e9 --- /dev/null +++ b/src/courier/types/automation_template_list_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel +from .automation_template import AutomationTemplate + +__all__ = ["AutomationTemplateListResponse"] + + +class AutomationTemplateListResponse(BaseModel): + cursor: Optional[str] = None + """A cursor token for pagination. Present when there are more results available.""" + + templates: Optional[List[AutomationTemplate]] = None diff --git a/src/courier/types/automations/__init__.py b/src/courier/types/automations/__init__.py new file mode 100644 index 00000000..930ff168 --- /dev/null +++ b/src/courier/types/automations/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .invoke_invoke_ad_hoc_params import InvokeInvokeAdHocParams as InvokeInvokeAdHocParams +from .invoke_invoke_by_template_params import InvokeInvokeByTemplateParams as InvokeInvokeByTemplateParams diff --git a/src/courier/types/automations/invoke_invoke_ad_hoc_params.py b/src/courier/types/automations/invoke_invoke_ad_hoc_params.py new file mode 100644 index 00000000..d2d903c8 --- /dev/null +++ b/src/courier/types/automations/invoke_invoke_ad_hoc_params.py @@ -0,0 +1,129 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from ..._utils import PropertyInfo + +__all__ = [ + "InvokeInvokeAdHocParams", + "Automation", + "AutomationStep", + "AutomationStepAutomationDelayStep", + "AutomationStepAutomationSendStep", + "AutomationStepAutomationSendListStep", + "AutomationStepAutomationUpdateProfileStep", + "AutomationStepAutomationCancelStep", + "AutomationStepAutomationFetchDataStep", + "AutomationStepAutomationFetchDataStepWebhook", + "AutomationStepAutomationInvokeStep", +] + + +class InvokeInvokeAdHocParams(TypedDict, total=False): + automation: Required[Automation] + + brand: Optional[str] + + data: Optional[Dict[str, object]] + + profile: Optional[Dict[str, object]] + + recipient: Optional[str] + + template: Optional[str] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +class AutomationStepAutomationDelayStep(TypedDict, total=False): + action: Required[Literal["delay"]] + + duration: Optional[str] + + until: Optional[str] + + +class AutomationStepAutomationSendStep(TypedDict, total=False): + action: Required[Literal["send"]] + + brand: Optional[str] + + data: Optional[Dict[str, object]] + + profile: Optional[Dict[str, object]] + + recipient: Optional[str] + + template: Optional[str] + + +class AutomationStepAutomationSendListStep(TypedDict, total=False): + action: Required[Literal["send-list"]] + + list: Required[str] + + brand: Optional[str] + + data: Optional[Dict[str, object]] + + +class AutomationStepAutomationUpdateProfileStep(TypedDict, total=False): + action: Required[Literal["update-profile"]] + + profile: Required[Dict[str, object]] + + merge: Optional[Literal["none", "overwrite", "soft-merge", "replace"]] + + recipient_id: Optional[str] + + +class AutomationStepAutomationCancelStep(TypedDict, total=False): + action: Required[Literal["cancel"]] + + cancelation_token: Required[str] + + +class AutomationStepAutomationFetchDataStepWebhook(TypedDict, total=False): + method: Required[Literal["GET", "POST", "PUT", "PATCH", "DELETE"]] + + url: Required[str] + + body: Optional[str] + + headers: Optional[Dict[str, str]] + + +class AutomationStepAutomationFetchDataStep(TypedDict, total=False): + action: Required[Literal["fetch-data"]] + + webhook: Required[AutomationStepAutomationFetchDataStepWebhook] + + merge_strategy: Optional[Literal["replace", "overwrite", "soft-merge"]] + + +class AutomationStepAutomationInvokeStep(TypedDict, total=False): + action: Required[Literal["invoke"]] + + template: Required[str] + + +AutomationStep: TypeAlias = Union[ + AutomationStepAutomationDelayStep, + AutomationStepAutomationSendStep, + AutomationStepAutomationSendListStep, + AutomationStepAutomationUpdateProfileStep, + AutomationStepAutomationCancelStep, + AutomationStepAutomationFetchDataStep, + AutomationStepAutomationInvokeStep, +] + + +class Automation(TypedDict, total=False): + steps: Required[Iterable[AutomationStep]] + + cancelation_token: Optional[str] diff --git a/src/courier/types/automations/invoke_invoke_by_template_params.py b/src/courier/types/automations/invoke_invoke_by_template_params.py new file mode 100644 index 00000000..5a98e774 --- /dev/null +++ b/src/courier/types/automations/invoke_invoke_by_template_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo + +__all__ = ["InvokeInvokeByTemplateParams"] + + +class InvokeInvokeByTemplateParams(TypedDict, total=False): + recipient: Required[Optional[str]] + + brand: Optional[str] + + data: Optional[Dict[str, object]] + + profile: Optional[Dict[str, object]] + + template: Optional[str] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/base_check.py b/src/courier/types/base_check.py new file mode 100644 index 00000000..7cead4e0 --- /dev/null +++ b/src/courier/types/base_check.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BaseCheck"] + + +class BaseCheck(BaseModel): + id: str + + status: Literal["RESOLVED", "FAILED", "PENDING"] + + type: Literal["custom"] diff --git a/src/courier/types/base_check_param.py b/src/courier/types/base_check_param.py new file mode 100644 index 00000000..8aca74f7 --- /dev/null +++ b/src/courier/types/base_check_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BaseCheckParam"] + + +class BaseCheckParam(TypedDict, total=False): + id: Required[str] + + status: Required[Literal["RESOLVED", "FAILED", "PENDING"]] + + type: Required[Literal["custom"]] diff --git a/src/courier/types/base_template_tenant_association.py b/src/courier/types/base_template_tenant_association.py new file mode 100644 index 00000000..1fd24e6a --- /dev/null +++ b/src/courier/types/base_template_tenant_association.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["BaseTemplateTenantAssociation"] + + +class BaseTemplateTenantAssociation(BaseModel): + id: str + """The template's id""" + + created_at: str + """The timestamp at which the template was created""" + + published_at: str + """The timestamp at which the template was published""" + + updated_at: str + """The timestamp at which the template was last updated""" + + version: str + """The version of the template""" diff --git a/src/courier/types/brand.py b/src/courier/types/brand.py new file mode 100644 index 00000000..b2b89db7 --- /dev/null +++ b/src/courier/types/brand.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel +from .brand_settings import BrandSettings +from .brand_snippets import BrandSnippets + +__all__ = ["Brand"] + + +class Brand(BaseModel): + id: str + + created: int + + name: str + + updated: int + + published: Optional[int] = None + + settings: Optional[BrandSettings] = None + + snippets: Optional[BrandSnippets] = None + + version: Optional[str] = None diff --git a/src/courier/types/brand_colors.py b/src/courier/types/brand_colors.py new file mode 100644 index 00000000..8170e1e7 --- /dev/null +++ b/src/courier/types/brand_colors.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import TYPE_CHECKING, Dict, Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["BrandColors"] + + +class BrandColors(BaseModel): + primary: Optional[str] = None + + secondary: Optional[str] = None + + if TYPE_CHECKING: + # Some versions of Pydantic <2.8.0 have a bug and don’t allow assigning a + # value to this field, so for compatibility we avoid doing it at runtime. + __pydantic_extra__: Dict[str, str] = FieldInfo(init=False) # pyright: ignore[reportIncompatibleVariableOverride] + + # Stub to indicate that arbitrary properties are accepted. + # To access properties that are not valid identifiers you can use `getattr`, e.g. + # `getattr(obj, '$type')` + def __getattr__(self, attr: str) -> str: ... + else: + __pydantic_extra__: Dict[str, str] diff --git a/src/courier/types/brand_colors_param.py b/src/courier/types/brand_colors_param.py new file mode 100644 index 00000000..109ab259 --- /dev/null +++ b/src/courier/types/brand_colors_param.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BrandColorsParam"] + + +class BrandColorsParam( # type: ignore[call-arg] + TypedDict, + total=False, + extra_items=str, # pyright: ignore[reportGeneralTypeIssues] +): + primary: str + + secondary: str diff --git a/src/courier/types/brand_create_params.py b/src/courier/types/brand_create_params.py new file mode 100644 index 00000000..5afcc3fe --- /dev/null +++ b/src/courier/types/brand_create_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .brand_settings_param import BrandSettingsParam +from .brand_snippets_param import BrandSnippetsParam + +__all__ = ["BrandCreateParams"] + + +class BrandCreateParams(TypedDict, total=False): + name: Required[str] + + settings: Required[BrandSettingsParam] + + id: Optional[str] + + snippets: Optional[BrandSnippetsParam] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/brand_list_params.py b/src/courier/types/brand_list_params.py new file mode 100644 index 00000000..abeb516d --- /dev/null +++ b/src/courier/types/brand_list_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["BrandListParams"] + + +class BrandListParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of brands.""" diff --git a/src/courier/types/brand_list_response.py b/src/courier/types/brand_list_response.py new file mode 100644 index 00000000..40aae82f --- /dev/null +++ b/src/courier/types/brand_list_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .brand import Brand +from .._models import BaseModel +from .shared.paging import Paging + +__all__ = ["BrandListResponse"] + + +class BrandListResponse(BaseModel): + paging: Paging + + results: List[Brand] diff --git a/src/courier/types/brand_settings.py b/src/courier/types/brand_settings.py new file mode 100644 index 00000000..4877bc5a --- /dev/null +++ b/src/courier/types/brand_settings.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel +from .brand_colors import BrandColors +from .brand_settings_email import BrandSettingsEmail +from .brand_settings_in_app import BrandSettingsInApp + +__all__ = ["BrandSettings"] + + +class BrandSettings(BaseModel): + colors: Optional[BrandColors] = None + + email: Optional[BrandSettingsEmail] = None + + inapp: Optional[BrandSettingsInApp] = None diff --git a/src/courier/types/brand_settings_email.py b/src/courier/types/brand_settings_email.py new file mode 100644 index 00000000..93e97081 --- /dev/null +++ b/src/courier/types/brand_settings_email.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel +from .email_head import EmailHead +from .email_footer import EmailFooter +from .email_header import EmailHeader +from .brand_template import BrandTemplate + +__all__ = ["BrandSettingsEmail", "TemplateOverride"] + + +class TemplateOverride(BrandTemplate): + mjml: BrandTemplate + + footer_background_color: Optional[str] = FieldInfo(alias="footerBackgroundColor", default=None) + + footer_full_width: Optional[bool] = FieldInfo(alias="footerFullWidth", default=None) + + +class BrandSettingsEmail(BaseModel): + footer: Optional[EmailFooter] = None + + head: Optional[EmailHead] = None + + header: Optional[EmailHeader] = None + + template_override: Optional[TemplateOverride] = FieldInfo(alias="templateOverride", default=None) diff --git a/src/courier/types/brand_settings_email_param.py b/src/courier/types/brand_settings_email_param.py new file mode 100644 index 00000000..018df3a4 --- /dev/null +++ b/src/courier/types/brand_settings_email_param.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .email_head_param import EmailHeadParam +from .email_footer_param import EmailFooterParam +from .email_header_param import EmailHeaderParam +from .brand_template_param import BrandTemplateParam + +__all__ = ["BrandSettingsEmailParam", "TemplateOverride"] + + +class TemplateOverride(BrandTemplateParam, total=False): + mjml: Required[BrandTemplateParam] + + footer_background_color: Annotated[Optional[str], PropertyInfo(alias="footerBackgroundColor")] + + footer_full_width: Annotated[Optional[bool], PropertyInfo(alias="footerFullWidth")] + + +class BrandSettingsEmailParam(TypedDict, total=False): + footer: Optional[EmailFooterParam] + + head: Optional[EmailHeadParam] + + header: Optional[EmailHeaderParam] + + template_override: Annotated[Optional[TemplateOverride], PropertyInfo(alias="templateOverride")] diff --git a/src/courier/types/brand_settings_in_app.py b/src/courier/types/brand_settings_in_app.py new file mode 100644 index 00000000..891bc6ff --- /dev/null +++ b/src/courier/types/brand_settings_in_app.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .icons import Icons +from .._models import BaseModel +from .brand_colors import BrandColors +from .widget_background import WidgetBackground + +__all__ = ["BrandSettingsInApp"] + + +class BrandSettingsInApp(BaseModel): + colors: BrandColors + + icons: Icons + + widget_background: WidgetBackground = FieldInfo(alias="widgetBackground") + + border_radius: Optional[str] = FieldInfo(alias="borderRadius", default=None) + + disable_message_icon: Optional[bool] = FieldInfo(alias="disableMessageIcon", default=None) + + font_family: Optional[str] = FieldInfo(alias="fontFamily", default=None) + + placement: Optional[Literal["top", "bottom", "left", "right"]] = None diff --git a/src/courier/types/brand_settings_in_app_param.py b/src/courier/types/brand_settings_in_app_param.py new file mode 100644 index 00000000..166d50a8 --- /dev/null +++ b/src/courier/types/brand_settings_in_app_param.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .icons_param import IconsParam +from .brand_colors_param import BrandColorsParam +from .widget_background_param import WidgetBackgroundParam + +__all__ = ["BrandSettingsInAppParam"] + + +class BrandSettingsInAppParam(TypedDict, total=False): + colors: Required[BrandColorsParam] + + icons: Required[IconsParam] + + widget_background: Required[Annotated[WidgetBackgroundParam, PropertyInfo(alias="widgetBackground")]] + + border_radius: Annotated[Optional[str], PropertyInfo(alias="borderRadius")] + + disable_message_icon: Annotated[Optional[bool], PropertyInfo(alias="disableMessageIcon")] + + font_family: Annotated[Optional[str], PropertyInfo(alias="fontFamily")] + + placement: Optional[Literal["top", "bottom", "left", "right"]] diff --git a/src/courier/types/brand_settings_param.py b/src/courier/types/brand_settings_param.py new file mode 100644 index 00000000..28f6c686 --- /dev/null +++ b/src/courier/types/brand_settings_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +from .brand_colors_param import BrandColorsParam +from .brand_settings_email_param import BrandSettingsEmailParam +from .brand_settings_in_app_param import BrandSettingsInAppParam + +__all__ = ["BrandSettingsParam"] + + +class BrandSettingsParam(TypedDict, total=False): + colors: Optional[BrandColorsParam] + + email: Optional[BrandSettingsEmailParam] + + inapp: Optional[BrandSettingsInAppParam] diff --git a/src/courier/types/brand_snippet.py b/src/courier/types/brand_snippet.py new file mode 100644 index 00000000..29ee5978 --- /dev/null +++ b/src/courier/types/brand_snippet.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["BrandSnippet"] + + +class BrandSnippet(BaseModel): + name: str + + value: str diff --git a/src/courier/types/brand_snippet_param.py b/src/courier/types/brand_snippet_param.py new file mode 100644 index 00000000..7716d79b --- /dev/null +++ b/src/courier/types/brand_snippet_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["BrandSnippetParam"] + + +class BrandSnippetParam(TypedDict, total=False): + name: Required[str] + + value: Required[str] diff --git a/src/courier/types/brand_snippets.py b/src/courier/types/brand_snippets.py new file mode 100644 index 00000000..4cc04377 --- /dev/null +++ b/src/courier/types/brand_snippets.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel +from .brand_snippet import BrandSnippet + +__all__ = ["BrandSnippets"] + + +class BrandSnippets(BaseModel): + items: Optional[List[BrandSnippet]] = None diff --git a/src/courier/types/brand_snippets_param.py b/src/courier/types/brand_snippets_param.py new file mode 100644 index 00000000..55e95c27 --- /dev/null +++ b/src/courier/types/brand_snippets_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import TypedDict + +from .brand_snippet_param import BrandSnippetParam + +__all__ = ["BrandSnippetsParam"] + + +class BrandSnippetsParam(TypedDict, total=False): + items: Optional[Iterable[BrandSnippetParam]] diff --git a/src/courier/types/brand_template.py b/src/courier/types/brand_template.py new file mode 100644 index 00000000..9d75b63d --- /dev/null +++ b/src/courier/types/brand_template.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["BrandTemplate"] + + +class BrandTemplate(BaseModel): + enabled: bool + + background_color: Optional[str] = FieldInfo(alias="backgroundColor", default=None) + + blocks_background_color: Optional[str] = FieldInfo(alias="blocksBackgroundColor", default=None) + + footer: Optional[str] = None + + head: Optional[str] = None + + header: Optional[str] = None + + width: Optional[str] = None diff --git a/src/courier/types/brand_template_param.py b/src/courier/types/brand_template_param.py new file mode 100644 index 00000000..5531f03e --- /dev/null +++ b/src/courier/types/brand_template_param.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["BrandTemplateParam"] + + +class BrandTemplateParam(TypedDict, total=False): + enabled: Required[bool] + + background_color: Annotated[Optional[str], PropertyInfo(alias="backgroundColor")] + + blocks_background_color: Annotated[Optional[str], PropertyInfo(alias="blocksBackgroundColor")] + + footer: Optional[str] + + head: Optional[str] + + header: Optional[str] + + width: Optional[str] diff --git a/src/courier/types/brand_update_params.py b/src/courier/types/brand_update_params.py new file mode 100644 index 00000000..188a5e09 --- /dev/null +++ b/src/courier/types/brand_update_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from .brand_settings_param import BrandSettingsParam +from .brand_snippets_param import BrandSnippetsParam + +__all__ = ["BrandUpdateParams"] + + +class BrandUpdateParams(TypedDict, total=False): + name: Required[str] + """The name of the brand.""" + + settings: Optional[BrandSettingsParam] + + snippets: Optional[BrandSnippetsParam] diff --git a/src/courier/types/broadcast.py b/src/courier/types/broadcast.py new file mode 100644 index 00000000..b736a130 --- /dev/null +++ b/src/courier/types/broadcast.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .broadcast_schedule import BroadcastSchedule + +__all__ = ["Broadcast"] + + +class Broadcast(BaseModel): + """ + A broadcast — a single-channel message delivered to a known set of recipients (a list or audience). + """ + + id: str + """The broadcast ID (bst\\__ prefix).""" + + channel: Literal["email", "sms", "push", "inbox", "slack", "msteams"] + """The broadcast's delivery channel.""" + + created_at: str + """ISO 8601 timestamp when the broadcast was created.""" + + created_by: str + """Actor that created the broadcast.""" + + name: str + """Human-readable name.""" + + status: Literal["draft", "scheduled", "sending", "sent"] + """Lifecycle status of the broadcast.""" + + updated_at: str + """ISO 8601 timestamp of the last update.""" + + updated_by: str + """Actor that last updated the broadcast.""" + + archived_at: Optional[str] = None + """ISO 8601 timestamp when the broadcast was archived, if archived.""" + + archived_by: Optional[str] = None + """Actor that archived the broadcast, if archived.""" + + schedule: Optional[BroadcastSchedule] = None + """The delivery schedule and recipient targeting for a broadcast.""" diff --git a/src/courier/types/broadcast_create_params.py b/src/courier/types/broadcast_create_params.py new file mode 100644 index 00000000..330ab8be --- /dev/null +++ b/src/courier/types/broadcast_create_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BroadcastCreateParams"] + + +class BroadcastCreateParams(TypedDict, total=False): + channel: Required[Literal["email", "sms", "push", "inbox", "slack", "msteams"]] + """The single delivery channel for this broadcast.""" + + name: Required[str] + """Human-readable name.""" diff --git a/src/courier/types/broadcast_list_params.py b/src/courier/types/broadcast_list_params.py new file mode 100644 index 00000000..9d89f6c8 --- /dev/null +++ b/src/courier/types/broadcast_list_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["BroadcastListParams"] + + +class BroadcastListParams(TypedDict, total=False): + cursor: Optional[str] + """Opaque pagination cursor from a previous response. Omit for the first page.""" + + limit: int + """Maximum number of results per page.""" diff --git a/src/courier/types/broadcast_list_response.py b/src/courier/types/broadcast_list_response.py new file mode 100644 index 00000000..acaa0322 --- /dev/null +++ b/src/courier/types/broadcast_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .broadcast import Broadcast +from .shared.paging import Paging + +__all__ = ["BroadcastListResponse"] + + +class BroadcastListResponse(BaseModel): + """Paginated list of broadcasts.""" + + paging: Paging + + results: List[Broadcast] diff --git a/src/courier/types/broadcast_put_content_params.py b/src/courier/types/broadcast_put_content_params.py new file mode 100644 index 00000000..8825088b --- /dev/null +++ b/src/courier/types/broadcast_put_content_params.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from .notification_template_state import NotificationTemplateState +from .shared_params.elemental_node import ElementalNode + +__all__ = ["BroadcastPutContentParams", "Content"] + + +class BroadcastPutContentParams(TypedDict, total=False): + content: Required[Content] + """Elemental content payload. The server defaults `version` when omitted.""" + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" + + +class Content(TypedDict, total=False): + """Elemental content payload. The server defaults `version` when omitted.""" + + elements: Required[Iterable[ElementalNode]] + + version: str + """Content version identifier (e.g., `2022-01-01`). + + Optional; server defaults when omitted. + """ diff --git a/src/courier/types/broadcast_retrieve_content_params.py b/src/courier/types/broadcast_retrieve_content_params.py new file mode 100644 index 00000000..c3192a4d --- /dev/null +++ b/src/courier/types/broadcast_retrieve_content_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BroadcastRetrieveContentParams"] + + +class BroadcastRetrieveContentParams(TypedDict, total=False): + version: str + """Accepts `draft`, `published`, or a version string (e.g. + + `v001`). Defaults to `draft`. + """ diff --git a/src/courier/types/broadcast_schedule.py b/src/courier/types/broadcast_schedule.py new file mode 100644 index 00000000..f9073201 --- /dev/null +++ b/src/courier/types/broadcast_schedule.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["BroadcastSchedule"] + + +class BroadcastSchedule(BaseModel): + """The delivery schedule and recipient targeting for a broadcast.""" + + recipient_id: str + """ID of the target list or audience.""" + + recipient_type: Literal["list", "audience"] + """Whether the broadcast targets a list or an audience.""" + + scheduled_to: Optional[str] = None + """Wall-clock timestamp of the scheduled send, no timezone offset (e.g. + + "2026-07-21T20:00:00"). + """ + + timezone: Optional[str] = None + """IANA timezone for the scheduled send (e.g. America/New_York).""" diff --git a/src/courier/types/broadcast_schedule_params.py b/src/courier/types/broadcast_schedule_params.py new file mode 100644 index 00000000..4cc7f3e5 --- /dev/null +++ b/src/courier/types/broadcast_schedule_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BroadcastScheduleParams"] + + +class BroadcastScheduleParams(TypedDict, total=False): + recipient_id: Required[str] + """ID of the target list or audience.""" + + recipient_type: Required[Literal["list", "audience"]] + """Whether the broadcast targets a list or an audience.""" + + scheduled_to: Required[str] + """Wall-clock timestamp of the future send, no timezone offset (e.g. + + "2026-07-21T20:00:00"). The zone is given by `timezone`. + """ + + timezone: str + """IANA timezone for the scheduled send (e.g. America/New_York).""" diff --git a/src/courier/types/broadcast_send_params.py b/src/courier/types/broadcast_send_params.py new file mode 100644 index 00000000..07fa67ba --- /dev/null +++ b/src/courier/types/broadcast_send_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BroadcastSendParams"] + + +class BroadcastSendParams(TypedDict, total=False): + recipient_id: Required[str] + """ID of the target list or audience.""" + + recipient_type: Required[Literal["list", "audience"]] + """Whether the broadcast targets a list or an audience.""" diff --git a/src/courier/types/broadcast_update_params.py b/src/courier/types/broadcast_update_params.py new file mode 100644 index 00000000..7d4da505 --- /dev/null +++ b/src/courier/types/broadcast_update_params.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["BroadcastUpdateParams"] + + +class BroadcastUpdateParams(TypedDict, total=False): + name: Required[str] + """New human-readable name.""" diff --git a/src/courier/types/cancel_journey_request_param.py b/src/courier/types/cancel_journey_request_param.py new file mode 100644 index 00000000..20736ed8 --- /dev/null +++ b/src/courier/types/cancel_journey_request_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Required, TypeAlias, TypedDict + +__all__ = ["CancelJourneyRequestParam", "ByCancelationToken", "ByRunID"] + + +class ByCancelationToken(TypedDict, total=False): + cancelation_token: Required[str] + + +class ByRunID(TypedDict, total=False): + run_id: Required[str] + + +CancelJourneyRequestParam: TypeAlias = Union[ByCancelationToken, ByRunID] diff --git a/src/courier/types/cancel_journey_response.py b/src/courier/types/cancel_journey_response.py new file mode 100644 index 00000000..8d257ebd --- /dev/null +++ b/src/courier/types/cancel_journey_response.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .._models import BaseModel + +__all__ = ["CancelJourneyResponse", "TokenBranch", "RunIDBranch"] + + +class TokenBranch(BaseModel): + cancelation_token: str + + +class RunIDBranch(BaseModel): + run_id: str + + status: str + """The run's resulting status. + + `CANCELED` when the run was active and has been canceled; `PROCESSED` or `ERROR` + when the run had already finished and was left unchanged; `CANCELED` for an + already-canceled run. + """ + + +CancelJourneyResponse: TypeAlias = Union[TokenBranch, RunIDBranch] diff --git a/src/courier/types/check.py b/src/courier/types/check.py new file mode 100644 index 00000000..ed19e57d --- /dev/null +++ b/src/courier/types/check.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .base_check import BaseCheck + +__all__ = ["Check"] + + +class Check(BaseCheck): + updated: int diff --git a/src/courier/types/default_preferences.py b/src/courier/types/default_preferences.py new file mode 100644 index 00000000..808847e5 --- /dev/null +++ b/src/courier/types/default_preferences.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel +from .subscription_topic_new import SubscriptionTopicNew + +__all__ = ["DefaultPreferences", "Item"] + + +class Item(SubscriptionTopicNew): + id: str + """Topic ID""" + + +class DefaultPreferences(BaseModel): + items: Optional[List[Item]] = None diff --git a/src/courier/types/default_preferences_param.py b/src/courier/types/default_preferences_param.py new file mode 100644 index 00000000..1e20ab06 --- /dev/null +++ b/src/courier/types/default_preferences_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Required, TypedDict + +from .subscription_topic_new_param import SubscriptionTopicNewParam + +__all__ = ["DefaultPreferencesParam", "Item"] + + +class Item(SubscriptionTopicNewParam, total=False): + id: Required[str] + """Topic ID""" + + +class DefaultPreferencesParam(TypedDict, total=False): + items: Optional[Iterable[Item]] diff --git a/src/courier/types/digest_category.py b/src/courier/types/digest_category.py new file mode 100644 index 00000000..700bbfa2 --- /dev/null +++ b/src/courier/types/digest_category.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["DigestCategory"] + + +class DigestCategory(BaseModel): + category_key: str + """The key that identifies the category within the digest.""" + + retain: Literal["first", "last", "highest", "lowest", "none"] + """ + Which events to keep when the number of events exceeds the retention limit for + the category. + """ + + sort_key: Optional[str] = None + """The data key used to order events when `retain` is `highest` or `lowest`.""" diff --git a/src/courier/types/digest_instance.py b/src/courier/types/digest_instance.py new file mode 100644 index 00000000..e279712d --- /dev/null +++ b/src/courier/types/digest_instance.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .digest_category import DigestCategory + +__all__ = ["DigestInstance"] + + +class DigestInstance(BaseModel): + digest_instance_id: str + """A unique identifier for the digest instance.""" + + event_count: int + """The total number of events received for this instance.""" + + status: Literal["IN_PROGRESS", "COMPLETED"] + """The status of the digest instance. + + `IN_PROGRESS` instances are still accumulating events; `COMPLETED` instances + have been released. + """ + + user_id: str + """The ID of the user this digest instance belongs to.""" + + categories: Optional[List[DigestCategory]] = None + """The categories configured for the digest.""" + + category_key_counts: Optional[Dict[str, int]] = None + """A map of category key to the number of events received for that category.""" + + created_at: Optional[str] = None + """An ISO 8601 timestamp of when the digest instance was created.""" + + disabled: Optional[bool] = None + """Whether the digest instance has been disabled.""" + + tenant_id: Optional[str] = None + """The ID of the tenant this digest instance belongs to, if any.""" diff --git a/src/courier/types/digest_instance_list_response.py b/src/courier/types/digest_instance_list_response.py new file mode 100644 index 00000000..cc1b11e9 --- /dev/null +++ b/src/courier/types/digest_instance_list_response.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .digest_instance import DigestInstance + +__all__ = ["DigestInstanceListResponse"] + + +class DigestInstanceListResponse(BaseModel): + has_more: bool + """Whether there are more digest instances to fetch using the cursor.""" + + items: List[DigestInstance] + """The digest instances for this page of results.""" + + type: Literal["list"] + """Always `list` for a paginated list response.""" + + cursor: Optional[str] = None + """ + A cursor token for fetching the next page of results, or null when there are + none. + """ + + next_url: Optional[str] = None + """The path to fetch the next page of results, or null when there are none.""" + + url: Optional[str] = None + """The path of the current request.""" diff --git a/src/courier/types/digests/__init__.py b/src/courier/types/digests/__init__.py new file mode 100644 index 00000000..5b1c71ff --- /dev/null +++ b/src/courier/types/digests/__init__.py @@ -0,0 +1,5 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .schedule_list_instances_params import ScheduleListInstancesParams as ScheduleListInstancesParams diff --git a/src/courier/types/digests/schedule_list_instances_params.py b/src/courier/types/digests/schedule_list_instances_params.py new file mode 100644 index 00000000..e1c820d9 --- /dev/null +++ b/src/courier/types/digests/schedule_list_instances_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ScheduleListInstancesParams"] + + +class ScheduleListInstancesParams(TypedDict, total=False): + cursor: str + """ + A cursor token from a previous response, used to fetch the next page of results. + """ + + limit: int + """The maximum number of digest instances to return. + + Defaults to 20, with a maximum of 100. + """ diff --git a/src/courier/types/element_with_checksums.py b/src/courier/types/element_with_checksums.py new file mode 100644 index 00000000..91401276 --- /dev/null +++ b/src/courier/types/element_with_checksums.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, List, Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["ElementWithChecksums", "Locales"] + + +class Locales(BaseModel): + checksum: str + + +class ElementWithChecksums(BaseModel): + """ + An element with its content checksum and optional nested elements and locale checksums. + """ + + checksum: str + """MD5 hash of translatable content.""" + + type: str + """Element type (text, meta, action, etc.).""" + + id: Optional[str] = None + + elements: Optional[List["ElementWithChecksums"]] = None + """Nested child elements (for group-type elements).""" + + locales: Optional[Dict[str, Locales]] = None + """Locale-specific content with checksums.""" + + if TYPE_CHECKING: + # Some versions of Pydantic <2.8.0 have a bug and don’t allow assigning a + # value to this field, so for compatibility we avoid doing it at runtime. + __pydantic_extra__: Dict[str, object] = FieldInfo(init=False) # pyright: ignore[reportIncompatibleVariableOverride] + + # Stub to indicate that arbitrary properties are accepted. + # To access properties that are not valid identifiers you can use `getattr`, e.g. + # `getattr(obj, '$type')` + def __getattr__(self, attr: str) -> object: ... + else: + __pydantic_extra__: Dict[str, object] diff --git a/src/courier/types/email_footer.py b/src/courier/types/email_footer.py new file mode 100644 index 00000000..56a656f8 --- /dev/null +++ b/src/courier/types/email_footer.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["EmailFooter"] + + +class EmailFooter(BaseModel): + content: Optional[str] = None + + inherit_default: Optional[bool] = FieldInfo(alias="inheritDefault", default=None) diff --git a/src/courier/types/email_footer_param.py b/src/courier/types/email_footer_param.py new file mode 100644 index 00000000..b8326ca5 --- /dev/null +++ b/src/courier/types/email_footer_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["EmailFooterParam"] + + +class EmailFooterParam(TypedDict, total=False): + content: Optional[str] + + inherit_default: Annotated[Optional[bool], PropertyInfo(alias="inheritDefault")] diff --git a/src/courier/types/email_head.py b/src/courier/types/email_head.py new file mode 100644 index 00000000..55070489 --- /dev/null +++ b/src/courier/types/email_head.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["EmailHead"] + + +class EmailHead(BaseModel): + inherit_default: bool = FieldInfo(alias="inheritDefault") + + content: Optional[str] = None diff --git a/src/courier/types/email_head_param.py b/src/courier/types/email_head_param.py new file mode 100644 index 00000000..45028f93 --- /dev/null +++ b/src/courier/types/email_head_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["EmailHeadParam"] + + +class EmailHeadParam(TypedDict, total=False): + inherit_default: Required[Annotated[bool, PropertyInfo(alias="inheritDefault")]] + + content: Optional[str] diff --git a/src/courier/types/email_header.py b/src/courier/types/email_header.py new file mode 100644 index 00000000..3a904bc0 --- /dev/null +++ b/src/courier/types/email_header.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .logo import Logo +from .._models import BaseModel + +__all__ = ["EmailHeader"] + + +class EmailHeader(BaseModel): + logo: Logo + + bar_color: Optional[str] = FieldInfo(alias="barColor", default=None) + + inherit_default: Optional[bool] = FieldInfo(alias="inheritDefault", default=None) diff --git a/src/courier/types/email_header_param.py b/src/courier/types/email_header_param.py new file mode 100644 index 00000000..70a43c2a --- /dev/null +++ b/src/courier/types/email_header_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .logo_param import LogoParam + +__all__ = ["EmailHeaderParam"] + + +class EmailHeaderParam(TypedDict, total=False): + logo: Required[LogoParam] + + bar_color: Annotated[Optional[str], PropertyInfo(alias="barColor")] + + inherit_default: Annotated[Optional[bool], PropertyInfo(alias="inheritDefault")] diff --git a/src/courier/types/icons.py b/src/courier/types/icons.py new file mode 100644 index 00000000..97ce2606 --- /dev/null +++ b/src/courier/types/icons.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["Icons"] + + +class Icons(BaseModel): + bell: Optional[str] = None + + message: Optional[str] = None diff --git a/src/courier/types/icons_param.py b/src/courier/types/icons_param.py new file mode 100644 index 00000000..daf23575 --- /dev/null +++ b/src/courier/types/icons_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["IconsParam"] + + +class IconsParam(TypedDict, total=False): + bell: Optional[str] + + message: Optional[str] diff --git a/src/courier/types/inbound_track_event_params.py b/src/courier/types/inbound_track_event_params.py new file mode 100644 index 00000000..fe0ddceb --- /dev/null +++ b/src/courier/types/inbound_track_event_params.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["InboundTrackEventParams"] + + +class InboundTrackEventParams(TypedDict, total=False): + event: Required[str] + """A descriptive name of the event. + + This name will appear as a trigger in the Courier Automation Trigger node. + """ + + message_id: Required[Annotated[str, PropertyInfo(alias="messageId")]] + """A required unique identifier that will be used to de-duplicate requests. + + If not unique, will respond with 409 Conflict status + """ + + properties: Required[Dict[str, object]] + + type: Required[Literal["track"]] + + user_id: Annotated[Optional[str], PropertyInfo(alias="userId")] + """The user id associated with the track""" diff --git a/src/courier/types/inbound_track_event_response.py b/src/courier/types/inbound_track_event_response.py new file mode 100644 index 00000000..14d0cc96 --- /dev/null +++ b/src/courier/types/inbound_track_event_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["InboundTrackEventResponse"] + + +class InboundTrackEventResponse(BaseModel): + message_id: str = FieldInfo(alias="messageId") + """ + A successful call returns a `202` status code along with a `requestId` in the + response body. + """ diff --git a/src/courier/types/journey.py b/src/courier/types/journey.py new file mode 100644 index 00000000..b14f7e47 --- /dev/null +++ b/src/courier/types/journey.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["Journey"] + + +class Journey(BaseModel): + """A journey template representing an automation workflow.""" + + id: str + """The unique identifier of the journey.""" + + name: str + """The name of the journey.""" + + version: Literal["published", "draft"] + """The version of the journey (published or draft).""" + + created_at: Optional[datetime] = FieldInfo(alias="createdAt", default=None) + """ISO 8601 timestamp when the journey was created.""" + + updated_at: Optional[datetime] = FieldInfo(alias="updatedAt", default=None) + """ISO 8601 timestamp when the journey was last updated.""" diff --git a/src/courier/types/journey_ai_node.py b/src/courier/types/journey_ai_node.py new file mode 100644 index 00000000..d836a4b2 --- /dev/null +++ b/src/courier/types/journey_ai_node.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyAINode"] + + +class JourneyAINode(BaseModel): + """Invoke an AI step with `user_prompt` and optional `web_search`. + + Returns a structured response conforming to `output_schema`. + """ + + output_schema: Dict[str, object] + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" + + type: Literal["ai"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + model: Optional[str] = None + + user_prompt: Optional[str] = None + + web_search: Optional[bool] = None diff --git a/src/courier/types/journey_ai_node_param.py b/src/courier/types/journey_ai_node_param.py new file mode 100644 index 00000000..79093ca9 --- /dev/null +++ b/src/courier/types/journey_ai_node_param.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyAINodeParam"] + + +class JourneyAINodeParam(TypedDict, total=False): + """Invoke an AI step with `user_prompt` and optional `web_search`. + + Returns a structured response conforming to `output_schema`. + """ + + output_schema: Required[Dict[str, object]] + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" + + type: Required[Literal["ai"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + model: str + + user_prompt: str + + web_search: bool diff --git a/src/courier/types/journey_api_invoke_trigger_node.py b/src/courier/types/journey_api_invoke_trigger_node.py new file mode 100644 index 00000000..fefbfda3 --- /dev/null +++ b/src/courier/types/journey_api_invoke_trigger_node.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyAPIInvokeTriggerNode"] + + +class JourneyAPIInvokeTriggerNode(BaseModel): + """Trigger fired when the journey is invoked via the API. + + The optional `schema` field is a JSON Schema that validates the invocation payload. + """ + + trigger_type: Literal["api-invoke"] + + type: Literal["trigger"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + schema_: Optional[Dict[str, object]] = FieldInfo(alias="schema", default=None) + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" diff --git a/src/courier/types/journey_api_invoke_trigger_node_param.py b/src/courier/types/journey_api_invoke_trigger_node_param.py new file mode 100644 index 00000000..f5cc604b --- /dev/null +++ b/src/courier/types/journey_api_invoke_trigger_node_param.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyAPIInvokeTriggerNodeParam"] + + +class JourneyAPIInvokeTriggerNodeParam(TypedDict, total=False): + """Trigger fired when the journey is invoked via the API. + + The optional `schema` field is a JSON Schema that validates the invocation payload. + """ + + trigger_type: Required[Literal["api-invoke"]] + + type: Required[Literal["trigger"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + schema: Dict[str, object] + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" diff --git a/src/courier/types/journey_cancel_params.py b/src/courier/types/journey_cancel_params.py new file mode 100644 index 00000000..e7eb6af5 --- /dev/null +++ b/src/courier/types/journey_cancel_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Required, Annotated, TypeAlias, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["JourneyCancelParams", "ByCancelationToken", "ByRunID"] + + +class ByCancelationToken(TypedDict, total=False): + cancelation_token: Required[str] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +class ByRunID(TypedDict, total=False): + run_id: Required[str] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +JourneyCancelParams: TypeAlias = Union[ByCancelationToken, ByRunID] diff --git a/src/courier/types/journey_condition_atom.py b/src/courier/types/journey_condition_atom.py new file mode 100644 index 00000000..d29571e4 --- /dev/null +++ b/src/courier/types/journey_condition_atom.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import TypeAlias + +__all__ = ["JourneyConditionAtom"] + +JourneyConditionAtom: TypeAlias = List[str] diff --git a/src/courier/types/journey_condition_atom_param.py b/src/courier/types/journey_condition_atom_param.py new file mode 100644 index 00000000..e23557f0 --- /dev/null +++ b/src/courier/types/journey_condition_atom_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import TypeAlias + +__all__ = ["JourneyConditionAtomParam", "JourneyConditionAtomParamItem"] + +JourneyConditionAtomParamItem: TypeAlias = str + +JourneyConditionAtomParam: TypeAlias = List[str] diff --git a/src/courier/types/journey_condition_group.py b/src/courier/types/journey_condition_group.py new file mode 100644 index 00000000..e2b26796 --- /dev/null +++ b/src/courier/types/journey_condition_group.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel +from .journey_condition_atom import JourneyConditionAtom + +__all__ = ["JourneyConditionGroup"] + + +class JourneyConditionGroup(BaseModel): + """A leaf condition group. + + Exactly one of `AND` or `OR` must be present at runtime; each is a list of `JourneyConditionAtom` tuples. + """ + + and_: Optional[List[JourneyConditionAtom]] = FieldInfo(alias="AND", default=None) + + or_: Optional[List[JourneyConditionAtom]] = FieldInfo(alias="OR", default=None) diff --git a/src/courier/types/journey_condition_group_param.py b/src/courier/types/journey_condition_group_param.py new file mode 100644 index 00000000..9067be7f --- /dev/null +++ b/src/courier/types/journey_condition_group_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo +from .journey_condition_atom_param import JourneyConditionAtomParam + +__all__ = ["JourneyConditionGroupParam"] + + +class JourneyConditionGroupParam(TypedDict, total=False): + """A leaf condition group. + + Exactly one of `AND` or `OR` must be present at runtime; each is a list of `JourneyConditionAtom` tuples. + """ + + and_: Annotated[Iterable[JourneyConditionAtomParam], PropertyInfo(alias="AND")] + + or_: Annotated[Iterable[JourneyConditionAtomParam], PropertyInfo(alias="OR")] diff --git a/src/courier/types/journey_condition_nested_group.py b/src/courier/types/journey_condition_nested_group.py new file mode 100644 index 00000000..c521bb16 --- /dev/null +++ b/src/courier/types/journey_condition_nested_group.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel +from .journey_condition_group import JourneyConditionGroup + +__all__ = ["JourneyConditionNestedGroup"] + + +class JourneyConditionNestedGroup(BaseModel): + """A nested condition group. + + Exactly one of `AND` or `OR` must be present at runtime; each is a list of `JourneyConditionGroup` items. + """ + + and_: Optional[List[JourneyConditionGroup]] = FieldInfo(alias="AND", default=None) + + or_: Optional[List[JourneyConditionGroup]] = FieldInfo(alias="OR", default=None) diff --git a/src/courier/types/journey_condition_nested_group_param.py b/src/courier/types/journey_condition_nested_group_param.py new file mode 100644 index 00000000..0465bde7 --- /dev/null +++ b/src/courier/types/journey_condition_nested_group_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo +from .journey_condition_group_param import JourneyConditionGroupParam + +__all__ = ["JourneyConditionNestedGroupParam"] + + +class JourneyConditionNestedGroupParam(TypedDict, total=False): + """A nested condition group. + + Exactly one of `AND` or `OR` must be present at runtime; each is a list of `JourneyConditionGroup` items. + """ + + and_: Annotated[Iterable[JourneyConditionGroupParam], PropertyInfo(alias="AND")] + + or_: Annotated[Iterable[JourneyConditionGroupParam], PropertyInfo(alias="OR")] diff --git a/src/courier/types/journey_conditions_field.py b/src/courier/types/journey_conditions_field.py new file mode 100644 index 00000000..e5e58e0c --- /dev/null +++ b/src/courier/types/journey_conditions_field.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .journey_condition_atom import JourneyConditionAtom +from .journey_condition_group import JourneyConditionGroup +from .journey_condition_nested_group import JourneyConditionNestedGroup + +__all__ = ["JourneyConditionsField"] + +JourneyConditionsField: TypeAlias = Union[JourneyConditionAtom, JourneyConditionGroup, JourneyConditionNestedGroup] diff --git a/src/courier/types/journey_conditions_field_param.py b/src/courier/types/journey_conditions_field_param.py new file mode 100644 index 00000000..258c8b73 --- /dev/null +++ b/src/courier/types/journey_conditions_field_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .journey_condition_atom_param import JourneyConditionAtomParam +from .journey_condition_group_param import JourneyConditionGroupParam +from .journey_condition_nested_group_param import JourneyConditionNestedGroupParam + +__all__ = ["JourneyConditionsFieldParam"] + +JourneyConditionsFieldParam: TypeAlias = Union[ + JourneyConditionAtomParam, JourneyConditionGroupParam, JourneyConditionNestedGroupParam +] diff --git a/src/courier/types/journey_create_params.py b/src/courier/types/journey_create_params.py new file mode 100644 index 00000000..bec2d0f0 --- /dev/null +++ b/src/courier/types/journey_create_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .journey_state import JourneyState + +__all__ = ["JourneyCreateParams"] + + +class JourneyCreateParams(TypedDict, total=False): + name: Required[str] + + nodes: Required[Iterable["JourneyNodeParam"]] + + enabled: bool + + state: JourneyState + """Lifecycle state of a journey.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +from .journey_node_param import JourneyNodeParam diff --git a/src/courier/types/journey_delay_duration_node.py b/src/courier/types/journey_delay_duration_node.py new file mode 100644 index 00000000..60e20bd6 --- /dev/null +++ b/src/courier/types/journey_delay_duration_node.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyDelayDurationNode"] + + +class JourneyDelayDurationNode(BaseModel): + """Pause the journey run for a fixed `duration`.""" + + duration: str + + mode: Literal["duration"] + + type: Literal["delay"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_delay_duration_node_param.py b/src/courier/types/journey_delay_duration_node_param.py new file mode 100644 index 00000000..38b0d51e --- /dev/null +++ b/src/courier/types/journey_delay_duration_node_param.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyDelayDurationNodeParam"] + + +class JourneyDelayDurationNodeParam(TypedDict, total=False): + """Pause the journey run for a fixed `duration`.""" + + duration: Required[str] + + mode: Required[Literal["duration"]] + + type: Required[Literal["delay"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_delay_until_node.py b/src/courier/types/journey_delay_until_node.py new file mode 100644 index 00000000..09da90d7 --- /dev/null +++ b/src/courier/types/journey_delay_until_node.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyDelayUntilNode"] + + +class JourneyDelayUntilNode(BaseModel): + """Pause the journey run `until` a specific time.""" + + mode: Literal["until"] + + type: Literal["delay"] + + until: str + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_delay_until_node_param.py b/src/courier/types/journey_delay_until_node_param.py new file mode 100644 index 00000000..35978be9 --- /dev/null +++ b/src/courier/types/journey_delay_until_node_param.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyDelayUntilNodeParam"] + + +class JourneyDelayUntilNodeParam(TypedDict, total=False): + """Pause the journey run `until` a specific time.""" + + mode: Required[Literal["until"]] + + type: Required[Literal["delay"]] + + until: Required[str] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_exit_node.py b/src/courier/types/journey_exit_node.py new file mode 100644 index 00000000..9339c93d --- /dev/null +++ b/src/courier/types/journey_exit_node.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["JourneyExitNode"] + + +class JourneyExitNode(BaseModel): + """Terminate the journey run.""" + + type: Literal["exit"] + + id: Optional[str] = None diff --git a/src/courier/types/journey_exit_node_param.py b/src/courier/types/journey_exit_node_param.py new file mode 100644 index 00000000..5a725dda --- /dev/null +++ b/src/courier/types/journey_exit_node_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["JourneyExitNodeParam"] + + +class JourneyExitNodeParam(TypedDict, total=False): + """Terminate the journey run.""" + + type: Required[Literal["exit"]] + + id: str diff --git a/src/courier/types/journey_experiment.py b/src/courier/types/journey_experiment.py new file mode 100644 index 00000000..14a29ac1 --- /dev/null +++ b/src/courier/types/journey_experiment.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel +from .journey_experiment_variant import JourneyExperimentVariant + +__all__ = ["JourneyExperiment"] + + +class JourneyExperiment(BaseModel): + """A/B experiment config for a send node. + + The recipient is deterministically bucketed by `bucketingKey` and routed to one of the `variants` in proportion to its `weight`. Present on a send node INSTEAD OF `message.template`. + """ + + bucketing_key: str = FieldInfo(alias="bucketingKey") + """The value used to deterministically assign a recipient to a variant. + + Must be non-empty with no leading or trailing whitespace. + """ + + variants: List[JourneyExperimentVariant] + """Between 2 and 10 weighted template variants.""" + + id: Optional[str] = None + """Unique experiment id (prefixed `exp_`). + + Omit to have one generated automatically; when supplied it must be a valid + `exp_` id. + """ + + name: Optional[str] = None + """Optional display name for the experiment.""" diff --git a/src/courier/types/journey_experiment_param.py b/src/courier/types/journey_experiment_param.py new file mode 100644 index 00000000..7f012b8d --- /dev/null +++ b/src/courier/types/journey_experiment_param.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .journey_experiment_variant_param import JourneyExperimentVariantParam + +__all__ = ["JourneyExperimentParam"] + + +class JourneyExperimentParam(TypedDict, total=False): + """A/B experiment config for a send node. + + The recipient is deterministically bucketed by `bucketingKey` and routed to one of the `variants` in proportion to its `weight`. Present on a send node INSTEAD OF `message.template`. + """ + + bucketing_key: Required[Annotated[str, PropertyInfo(alias="bucketingKey")]] + """The value used to deterministically assign a recipient to a variant. + + Must be non-empty with no leading or trailing whitespace. + """ + + variants: Required[Iterable[JourneyExperimentVariantParam]] + """Between 2 and 10 weighted template variants.""" + + id: str + """Unique experiment id (prefixed `exp_`). + + Omit to have one generated automatically; when supplied it must be a valid + `exp_` id. + """ + + name: str + """Optional display name for the experiment.""" diff --git a/src/courier/types/journey_experiment_variant.py b/src/courier/types/journey_experiment_variant.py new file mode 100644 index 00000000..134626a0 --- /dev/null +++ b/src/courier/types/journey_experiment_variant.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["JourneyExperimentVariant"] + + +class JourneyExperimentVariant(BaseModel): + """A single weighted variant of an experiment. + + Variant ids must be unique within the experiment and the sum of all variant weights must be greater than 0. Weights are relative (no sum-to-100 requirement) — routing normalizes them proportionally. + """ + + id: str + + template_id: str = FieldInfo(alias="templateId") + """The notification template sent for this variant.""" + + weight: float + """Relative routing weight. Must be non-negative.""" + + name: Optional[str] = None + """Optional display name for the variant.""" diff --git a/src/courier/types/journey_experiment_variant_param.py b/src/courier/types/journey_experiment_variant_param.py new file mode 100644 index 00000000..c31d5f56 --- /dev/null +++ b/src/courier/types/journey_experiment_variant_param.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["JourneyExperimentVariantParam"] + + +class JourneyExperimentVariantParam(TypedDict, total=False): + """A single weighted variant of an experiment. + + Variant ids must be unique within the experiment and the sum of all variant weights must be greater than 0. Weights are relative (no sum-to-100 requirement) — routing normalizes them proportionally. + """ + + id: Required[str] + + template_id: Required[Annotated[str, PropertyInfo(alias="templateId")]] + """The notification template sent for this variant.""" + + weight: Required[float] + """Relative routing weight. Must be non-negative.""" + + name: str + """Optional display name for the variant.""" diff --git a/src/courier/types/journey_fetch_get_delete_node.py b/src/courier/types/journey_fetch_get_delete_node.py new file mode 100644 index 00000000..5fdbdbb9 --- /dev/null +++ b/src/courier/types/journey_fetch_get_delete_node.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_merge_strategy import JourneyMergeStrategy +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyFetchGetDeleteNode"] + + +class JourneyFetchGetDeleteNode(BaseModel): + """ + Issue an HTTP GET or DELETE request and merge the response into the journey state per `merge_strategy`. + """ + + merge_strategy: JourneyMergeStrategy + """Strategy for merging a fetch response into the journey run state.""" + + method: Literal["get", "delete"] + + type: Literal["fetch"] + + url: str + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + headers: Optional[Dict[str, str]] = None + + query_params: Optional[Dict[str, str]] = None + + response_schema: Optional[Dict[str, object]] = None + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" diff --git a/src/courier/types/journey_fetch_get_delete_node_param.py b/src/courier/types/journey_fetch_get_delete_node_param.py new file mode 100644 index 00000000..642abba0 --- /dev/null +++ b/src/courier/types/journey_fetch_get_delete_node_param.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +from .journey_merge_strategy import JourneyMergeStrategy +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyFetchGetDeleteNodeParam"] + + +class JourneyFetchGetDeleteNodeParam(TypedDict, total=False): + """ + Issue an HTTP GET or DELETE request and merge the response into the journey state per `merge_strategy`. + """ + + merge_strategy: Required[JourneyMergeStrategy] + """Strategy for merging a fetch response into the journey run state.""" + + method: Required[Literal["get", "delete"]] + + type: Required[Literal["fetch"]] + + url: Required[str] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + headers: Dict[str, str] + + query_params: Dict[str, str] + + response_schema: Dict[str, object] + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" diff --git a/src/courier/types/journey_fetch_post_put_node.py b/src/courier/types/journey_fetch_post_put_node.py new file mode 100644 index 00000000..f1c91aae --- /dev/null +++ b/src/courier/types/journey_fetch_post_put_node.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_merge_strategy import JourneyMergeStrategy +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyFetchPostPutNode"] + + +class JourneyFetchPostPutNode(BaseModel): + """ + Issue an HTTP POST or PUT request with a `body` and merge the response into the journey state per `merge_strategy`. + """ + + merge_strategy: JourneyMergeStrategy + """Strategy for merging a fetch response into the journey run state.""" + + method: Literal["post", "put"] + + type: Literal["fetch"] + + url: str + + id: Optional[str] = None + + body: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + headers: Optional[Dict[str, str]] = None + + query_params: Optional[Dict[str, str]] = None + + response_schema: Optional[Dict[str, object]] = None + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" diff --git a/src/courier/types/journey_fetch_post_put_node_param.py b/src/courier/types/journey_fetch_post_put_node_param.py new file mode 100644 index 00000000..f07ad037 --- /dev/null +++ b/src/courier/types/journey_fetch_post_put_node_param.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +from .journey_merge_strategy import JourneyMergeStrategy +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyFetchPostPutNodeParam"] + + +class JourneyFetchPostPutNodeParam(TypedDict, total=False): + """ + Issue an HTTP POST or PUT request with a `body` and merge the response into the journey state per `merge_strategy`. + """ + + merge_strategy: Required[JourneyMergeStrategy] + """Strategy for merging a fetch response into the journey run state.""" + + method: Required[Literal["post", "put"]] + + type: Required[Literal["fetch"]] + + url: Required[str] + + id: str + + body: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + headers: Dict[str, str] + + query_params: Dict[str, str] + + response_schema: Dict[str, object] + """A JSONSchema object (Draft-07-compatible). Validated at runtime by Ajv.""" diff --git a/src/courier/types/journey_invoke_params.py b/src/courier/types/journey_invoke_params.py new file mode 100644 index 00000000..bfc187e1 --- /dev/null +++ b/src/courier/types/journey_invoke_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["JourneyInvokeParams"] + + +class JourneyInvokeParams(TypedDict, total=False): + data: Dict[str, object] + """Data payload passed to the journey. + + The expected shape can be predefined using the schema builder in the journey + editor. This data is available in journey steps for condition evaluation and + template variable interpolation. Can also contain user identifiers (user_id, + userId, anonymousId) if not provided elsewhere. + """ + + profile: Dict[str, object] + """Profile data for the user. + + Can contain contact information (email, phone_number), user identifiers + (user_id, userId, anonymousId), or any custom profile fields. Profile fields are + merged with any existing stored profile for the user. Include context.tenant_id + to load a tenant-scoped profile for multi-tenant scenarios. + """ + + user_id: str + """A unique identifier for the user. + + If not provided, the system will attempt to resolve the user identifier from + profile or data objects. + """ + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/journey_list_params.py b/src/courier/types/journey_list_params.py new file mode 100644 index 00000000..8184236c --- /dev/null +++ b/src/courier/types/journey_list_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["JourneyListParams"] + + +class JourneyListParams(TypedDict, total=False): + cursor: str + """A cursor token for pagination. + + Use the cursor from the previous response to fetch the next page of results. + """ + + version: Literal["published", "draft"] + """The version of journeys to retrieve. + + Accepted values are published (for published journeys) or draft (for draft + journeys). Defaults to published. + """ diff --git a/src/courier/types/journey_merge_strategy.py b/src/courier/types/journey_merge_strategy.py new file mode 100644 index 00000000..8c9fd787 --- /dev/null +++ b/src/courier/types/journey_merge_strategy.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["JourneyMergeStrategy"] + +JourneyMergeStrategy: TypeAlias = Literal["overwrite", "soft-merge", "replace", "none"] diff --git a/src/courier/types/journey_node.py b/src/courier/types/journey_node.py new file mode 100644 index 00000000..33420ba8 --- /dev/null +++ b/src/courier/types/journey_node.py @@ -0,0 +1,168 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Optional +from typing_extensions import Literal, TypeAlias + +from .._models import BaseModel +from .journey_ai_node import JourneyAINode +from .journey_exit_node import JourneyExitNode +from .journey_send_node import JourneySendNode +from .journey_conditions_field import JourneyConditionsField +from .journey_delay_until_node import JourneyDelayUntilNode +from .journey_delay_duration_node import JourneyDelayDurationNode +from .journey_fetch_post_put_node import JourneyFetchPostPutNode +from .journey_segment_trigger_node import JourneySegmentTriggerNode +from .journey_throttle_static_node import JourneyThrottleStaticNode +from .journey_fetch_get_delete_node import JourneyFetchGetDeleteNode +from .journey_throttle_dynamic_node import JourneyThrottleDynamicNode +from .journey_api_invoke_trigger_node import JourneyAPIInvokeTriggerNode + +__all__ = [ + "JourneyNode", + "JourneyBatchNode", + "JourneyBatchNodeRetain", + "JourneyAddToDigestNode", + "JourneyBranchNode", + "JourneyBranchNodeDefault", + "JourneyBranchNodePath", +] + + +class JourneyBatchNodeRetain(BaseModel): + """ + How to select which collected events to retain in the aggregated payload when the batch releases. + """ + + count: int + + type: Literal["first", "last", "highest", "lowest"] + + sort_key: Optional[str] = None + """Dot-path into the event payload (e.g. + + `data.priority`). Required when `type` is `highest` or `lowest`. + """ + + +class JourneyBatchNode(BaseModel): + """ + Collect events arriving at the node into a single batch and fire one downstream step with the aggregated payload. The first event into a batch owns the run; later contributing events terminate at the batch step. The batch releases when any of `max_items` is reached, a quiet window of `wait_period` elapses, or the `max_wait_period` ceiling hits. + """ + + max_wait_period: str + """ISO 8601 duration. + + Hard ceiling from the first event into the batch; releases the batch + unconditionally when it elapses. + """ + + retain: JourneyBatchNodeRetain + """ + How to select which collected events to retain in the aggregated payload when + the batch releases. + """ + + scope: Literal["user"] + + type: Literal["batch"] + + wait_period: str + """ISO 8601 duration. + + Quiet window that releases the batch when it elapses with no new contributing + events. Must be less than `max_wait_period`. + """ + + id: Optional[str] = None + + category_key: Optional[str] = None + """Optional partition key. + + Events with the same `category_key` are batched together; events with different + values are batched separately. + """ + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + max_items: Optional[int] = None + """Releases the batch once this many events have been collected.""" + + +class JourneyAddToDigestNode(BaseModel): + """Add the current event to a digest keyed by the given subscription topic. + + The digest accumulates events and releases them on the schedule configured for the topic. + """ + + subscription_topic_id: str + """The subscription topic that owns the digest the event is added to.""" + + type: Literal["add-to-digest"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + +class JourneyBranchNodeDefault(BaseModel): + nodes: List["JourneyNode"] + + label: Optional[str] = None + + +class JourneyBranchNodePath(BaseModel): + conditions: JourneyConditionsField + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + nodes: List["JourneyNode"] + + label: Optional[str] = None + + +class JourneyBranchNode(BaseModel): + """Branch node. + + Routes to the first entry in `paths[]` whose `conditions` match, else falls through to `default.nodes`. + """ + + default: JourneyBranchNodeDefault + + paths: List[JourneyBranchNodePath] + + type: Literal["branch"] + + id: Optional[str] = None + + +JourneyNode: TypeAlias = Union[ + JourneyAPIInvokeTriggerNode, + JourneySegmentTriggerNode, + JourneySendNode, + JourneyDelayDurationNode, + JourneyDelayUntilNode, + JourneyFetchGetDeleteNode, + JourneyFetchPostPutNode, + JourneyAINode, + JourneyThrottleStaticNode, + JourneyThrottleDynamicNode, + JourneyBatchNode, + JourneyAddToDigestNode, + JourneyExitNode, + JourneyBranchNode, +] diff --git a/src/courier/types/journey_node_param.py b/src/courier/types/journey_node_param.py new file mode 100644 index 00000000..65b0d1be --- /dev/null +++ b/src/courier/types/journey_node_param.py @@ -0,0 +1,167 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .journey_ai_node_param import JourneyAINodeParam +from .journey_exit_node_param import JourneyExitNodeParam +from .journey_send_node_param import JourneySendNodeParam +from .journey_conditions_field_param import JourneyConditionsFieldParam +from .journey_delay_until_node_param import JourneyDelayUntilNodeParam +from .journey_delay_duration_node_param import JourneyDelayDurationNodeParam +from .journey_fetch_post_put_node_param import JourneyFetchPostPutNodeParam +from .journey_segment_trigger_node_param import JourneySegmentTriggerNodeParam +from .journey_throttle_static_node_param import JourneyThrottleStaticNodeParam +from .journey_fetch_get_delete_node_param import JourneyFetchGetDeleteNodeParam +from .journey_throttle_dynamic_node_param import JourneyThrottleDynamicNodeParam +from .journey_api_invoke_trigger_node_param import JourneyAPIInvokeTriggerNodeParam + +__all__ = [ + "JourneyNodeParam", + "JourneyBatchNode", + "JourneyBatchNodeRetain", + "JourneyAddToDigestNode", + "JourneyBranchNode", + "JourneyBranchNodeDefault", + "JourneyBranchNodePath", +] + + +class JourneyBatchNodeRetain(TypedDict, total=False): + """ + How to select which collected events to retain in the aggregated payload when the batch releases. + """ + + count: Required[int] + + type: Required[Literal["first", "last", "highest", "lowest"]] + + sort_key: str + """Dot-path into the event payload (e.g. + + `data.priority`). Required when `type` is `highest` or `lowest`. + """ + + +class JourneyBatchNode(TypedDict, total=False): + """ + Collect events arriving at the node into a single batch and fire one downstream step with the aggregated payload. The first event into a batch owns the run; later contributing events terminate at the batch step. The batch releases when any of `max_items` is reached, a quiet window of `wait_period` elapses, or the `max_wait_period` ceiling hits. + """ + + max_wait_period: Required[str] + """ISO 8601 duration. + + Hard ceiling from the first event into the batch; releases the batch + unconditionally when it elapses. + """ + + retain: Required[JourneyBatchNodeRetain] + """ + How to select which collected events to retain in the aggregated payload when + the batch releases. + """ + + scope: Required[Literal["user"]] + + type: Required[Literal["batch"]] + + wait_period: Required[str] + """ISO 8601 duration. + + Quiet window that releases the batch when it elapses with no new contributing + events. Must be less than `max_wait_period`. + """ + + id: str + + category_key: str + """Optional partition key. + + Events with the same `category_key` are batched together; events with different + values are batched separately. + """ + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + max_items: int + """Releases the batch once this many events have been collected.""" + + +class JourneyAddToDigestNode(TypedDict, total=False): + """Add the current event to a digest keyed by the given subscription topic. + + The digest accumulates events and releases them on the schedule configured for the topic. + """ + + subscription_topic_id: Required[str] + """The subscription topic that owns the digest the event is added to.""" + + type: Required[Literal["add-to-digest"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + +class JourneyBranchNodeDefault(TypedDict, total=False): + nodes: Required[Iterable["JourneyNodeParam"]] + + label: str + + +class JourneyBranchNodePath(TypedDict, total=False): + conditions: Required[JourneyConditionsFieldParam] + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + nodes: Required[Iterable["JourneyNodeParam"]] + + label: str + + +class JourneyBranchNode(TypedDict, total=False): + """Branch node. + + Routes to the first entry in `paths[]` whose `conditions` match, else falls through to `default.nodes`. + """ + + default: Required[JourneyBranchNodeDefault] + + paths: Required[Iterable[JourneyBranchNodePath]] + + type: Required[Literal["branch"]] + + id: str + + +JourneyNodeParam: TypeAlias = Union[ + JourneyAPIInvokeTriggerNodeParam, + JourneySegmentTriggerNodeParam, + JourneySendNodeParam, + JourneyDelayDurationNodeParam, + JourneyDelayUntilNodeParam, + JourneyFetchGetDeleteNodeParam, + JourneyFetchPostPutNodeParam, + JourneyAINodeParam, + JourneyThrottleStaticNodeParam, + JourneyThrottleDynamicNodeParam, + JourneyBatchNode, + JourneyAddToDigestNode, + JourneyExitNodeParam, + JourneyBranchNode, +] diff --git a/src/courier/types/journey_publish_params.py b/src/courier/types/journey_publish_params.py new file mode 100644 index 00000000..c0f6b89c --- /dev/null +++ b/src/courier/types/journey_publish_params.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["JourneyPublishParams"] + + +class JourneyPublishParams(TypedDict, total=False): + version: str + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/journey_replace_params.py b/src/courier/types/journey_replace_params.py new file mode 100644 index 00000000..f19a65f1 --- /dev/null +++ b/src/courier/types/journey_replace_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from .journey_state import JourneyState + +__all__ = ["JourneyReplaceParams"] + + +class JourneyReplaceParams(TypedDict, total=False): + name: Required[str] + + nodes: Required[Iterable["JourneyNodeParam"]] + + enabled: bool + + state: JourneyState + """Lifecycle state of a journey.""" + + +from .journey_node_param import JourneyNodeParam diff --git a/src/courier/types/journey_response.py b/src/courier/types/journey_response.py new file mode 100644 index 00000000..afa83bf2 --- /dev/null +++ b/src/courier/types/journey_response.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional + +from .._models import BaseModel +from .journey_state import JourneyState + +__all__ = ["JourneyResponse"] + + +class JourneyResponse(BaseModel): + """A journey, with its current draft or published nodes and metadata.""" + + id: str + + created: Optional[int] = None + + creator: Optional[str] = None + + enabled: bool + + name: str + + nodes: List["JourneyNode"] + + published: Optional[int] = None + + state: JourneyState + """Lifecycle state of a journey.""" + + updated: Optional[int] = None + + updater: Optional[str] = None + + +from .journey_node import JourneyNode diff --git a/src/courier/types/journey_retrieve_params.py b/src/courier/types/journey_retrieve_params.py new file mode 100644 index 00000000..b2f5528b --- /dev/null +++ b/src/courier/types/journey_retrieve_params.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["JourneyRetrieveParams"] + + +class JourneyRetrieveParams(TypedDict, total=False): + version: str + """Version selector: `draft`, `published` (default), or `vN`.""" diff --git a/src/courier/types/journey_segment_trigger_node.py b/src/courier/types/journey_segment_trigger_node.py new file mode 100644 index 00000000..74fb1866 --- /dev/null +++ b/src/courier/types/journey_segment_trigger_node.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneySegmentTriggerNode"] + + +class JourneySegmentTriggerNode(BaseModel): + """Trigger fired by a segment event (`identify`, `group`, or `track`).""" + + request_type: Literal["identify", "group", "track"] + + trigger_type: Literal["segment"] + + type: Literal["trigger"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + event_id: Optional[str] = None diff --git a/src/courier/types/journey_segment_trigger_node_param.py b/src/courier/types/journey_segment_trigger_node_param.py new file mode 100644 index 00000000..2dcbba28 --- /dev/null +++ b/src/courier/types/journey_segment_trigger_node_param.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneySegmentTriggerNodeParam"] + + +class JourneySegmentTriggerNodeParam(TypedDict, total=False): + """Trigger fired by a segment event (`identify`, `group`, or `track`).""" + + request_type: Required[Literal["identify", "group", "track"]] + + trigger_type: Required[Literal["segment"]] + + type: Required[Literal["trigger"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + event_id: str diff --git a/src/courier/types/journey_send_node.py b/src/courier/types/journey_send_node.py new file mode 100644 index 00000000..c60900ab --- /dev/null +++ b/src/courier/types/journey_send_node.py @@ -0,0 +1,91 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_experiment import JourneyExperiment +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneySendNode", "Message", "MessageContext", "MessageDelay", "MessageTo"] + + +class MessageContext(BaseModel): + """Tenant context for this send. + + Set it to deliver on behalf of one of your customers, so the message uses that tenant's brand and settings. + """ + + tenant_id: str + """The tenant to send as. + + Accepts either a literal tenant id (`acme-tenant`) or a whole-string mustache + reference to a value the run already holds — `{{data.tenant_id}}` from the + invocation payload, or `{{f1.body.tenant_id}}` from the response of an earlier + fetch node with id `f1`. A reference is resolved separately on every run, so a + single journey can deliver as many tenants. Two forms are rejected with `400`: + mid-string interpolation such as `tenant-{{data.region}}`, and any value + beginning with `refs.`, which is reserved for internal use. A reference that + resolves to nothing at run time does not stop the run — the message is still + sent, with no tenant context — so make sure the referenced value is always + present. `GET` returns the value in the same form it was supplied. + """ + + +class MessageDelay(BaseModel): + until: str + + timezone: Optional[str] = None + + +class MessageTo(BaseModel): + email_override: Optional[str] = None + + phone_number_override: Optional[str] = None + + user_id_override: Optional[str] = None + + +class Message(BaseModel): + context: Optional[MessageContext] = None + """Tenant context for this send. + + Set it to deliver on behalf of one of your customers, so the message uses that + tenant's brand and settings. + """ + + data: Optional[Dict[str, object]] = None + + delay: Optional[MessageDelay] = None + + template: Optional[str] = None + + to: Optional[MessageTo] = None + + +class JourneySendNode(BaseModel): + """Send to the recipient. + + A send node sources its content from EXACTLY ONE of `message.template` (a single notification template) or `experiment` (an A/B split across weighted template variants) — supplying both, or neither, is rejected. Optionally override the recipient address, send as a tenant, delay the send, or attach `data`. + """ + + message: Message + + type: Literal["send"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + experiment: Optional[JourneyExperiment] = None + """A/B experiment config for a send node. + + The recipient is deterministically bucketed by `bucketingKey` and routed to one + of the `variants` in proportion to its `weight`. Present on a send node INSTEAD + OF `message.template`. + """ diff --git a/src/courier/types/journey_send_node_param.py b/src/courier/types/journey_send_node_param.py new file mode 100644 index 00000000..4a5069ca --- /dev/null +++ b/src/courier/types/journey_send_node_param.py @@ -0,0 +1,92 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +from .journey_experiment_param import JourneyExperimentParam +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneySendNodeParam", "Message", "MessageContext", "MessageDelay", "MessageTo"] + + +class MessageContext(TypedDict, total=False): + """Tenant context for this send. + + Set it to deliver on behalf of one of your customers, so the message uses that tenant's brand and settings. + """ + + tenant_id: Required[str] + """The tenant to send as. + + Accepts either a literal tenant id (`acme-tenant`) or a whole-string mustache + reference to a value the run already holds — `{{data.tenant_id}}` from the + invocation payload, or `{{f1.body.tenant_id}}` from the response of an earlier + fetch node with id `f1`. A reference is resolved separately on every run, so a + single journey can deliver as many tenants. Two forms are rejected with `400`: + mid-string interpolation such as `tenant-{{data.region}}`, and any value + beginning with `refs.`, which is reserved for internal use. A reference that + resolves to nothing at run time does not stop the run — the message is still + sent, with no tenant context — so make sure the referenced value is always + present. `GET` returns the value in the same form it was supplied. + """ + + +class MessageDelay(TypedDict, total=False): + until: Required[str] + + timezone: str + + +class MessageTo(TypedDict, total=False): + email_override: str + + phone_number_override: str + + user_id_override: str + + +class Message(TypedDict, total=False): + context: MessageContext + """Tenant context for this send. + + Set it to deliver on behalf of one of your customers, so the message uses that + tenant's brand and settings. + """ + + data: Dict[str, object] + + delay: MessageDelay + + template: str + + to: MessageTo + + +class JourneySendNodeParam(TypedDict, total=False): + """Send to the recipient. + + A send node sources its content from EXACTLY ONE of `message.template` (a single notification template) or `experiment` (an A/B split across weighted template variants) — supplying both, or neither, is rejected. Optionally override the recipient address, send as a tenant, delay the send, or attach `data`. + """ + + message: Required[Message] + + type: Required[Literal["send"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ + + experiment: JourneyExperimentParam + """A/B experiment config for a send node. + + The recipient is deterministically bucketed by `bucketingKey` and routed to one + of the `variants` in proportion to its `weight`. Present on a send node INSTEAD + OF `message.template`. + """ diff --git a/src/courier/types/journey_state.py b/src/courier/types/journey_state.py new file mode 100644 index 00000000..3aa34acb --- /dev/null +++ b/src/courier/types/journey_state.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["JourneyState"] + +JourneyState: TypeAlias = Literal["DRAFT", "PUBLISHED"] diff --git a/src/courier/types/journey_template_get_response.py b/src/courier/types/journey_template_get_response.py new file mode 100644 index 00000000..11137390 --- /dev/null +++ b/src/courier/types/journey_template_get_response.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .shared.elemental_node import ElementalNode + +__all__ = ["JourneyTemplateGetResponse", "Brand", "Content", "Subscription"] + + +class Brand(BaseModel): + id: str + + +class Content(BaseModel): + elements: List[ElementalNode] + + version: Literal["2022-01-01"] + + scope: Optional[Literal["default", "strict"]] = None + + +class Subscription(BaseModel): + topic_id: str + + +class JourneyTemplateGetResponse(BaseModel): + """A journey-scoped notification template.""" + + id: str + + brand: Optional[Brand] = None + + content: Content + + created: int + + creator: str + + name: str + + state: Literal["DRAFT", "PUBLISHED"] + + subscription: Optional[Subscription] = None + + tags: List[str] + + updated: Optional[int] = None + + updater: Optional[str] = None diff --git a/src/courier/types/journey_template_list_response.py b/src/courier/types/journey_template_list_response.py new file mode 100644 index 00000000..3f8a2feb --- /dev/null +++ b/src/courier/types/journey_template_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging +from .journey_template_summary import JourneyTemplateSummary + +__all__ = ["JourneyTemplateListResponse"] + + +class JourneyTemplateListResponse(BaseModel): + """Paged list of journey-scoped notification templates.""" + + paging: Paging + + results: List[JourneyTemplateSummary] diff --git a/src/courier/types/journey_template_summary.py b/src/courier/types/journey_template_summary.py new file mode 100644 index 00000000..d8b19186 --- /dev/null +++ b/src/courier/types/journey_template_summary.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["JourneyTemplateSummary"] + + +class JourneyTemplateSummary(BaseModel): + """ + Summary fields of a journey-scoped notification template returned in list responses. + """ + + id: str + + created: int + + creator: str + + name: str + + state: str + + tags: List[str] + + updated: Optional[int] = None + + updater: Optional[str] = None diff --git a/src/courier/types/journey_throttle_dynamic_node.py b/src/courier/types/journey_throttle_dynamic_node.py new file mode 100644 index 00000000..cea48b8d --- /dev/null +++ b/src/courier/types/journey_throttle_dynamic_node.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyThrottleDynamicNode"] + + +class JourneyThrottleDynamicNode(BaseModel): + """ + Throttle the journey by a dynamic `throttle_key`, allowing at most `max_allowed` invocations per `period`. + """ + + max_allowed: int + + period: str + + scope: Literal["dynamic"] + + throttle_key: str + + type: Literal["throttle"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_throttle_dynamic_node_param.py b/src/courier/types/journey_throttle_dynamic_node_param.py new file mode 100644 index 00000000..19124e71 --- /dev/null +++ b/src/courier/types/journey_throttle_dynamic_node_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyThrottleDynamicNodeParam"] + + +class JourneyThrottleDynamicNodeParam(TypedDict, total=False): + """ + Throttle the journey by a dynamic `throttle_key`, allowing at most `max_allowed` invocations per `period`. + """ + + max_allowed: Required[int] + + period: Required[str] + + scope: Required[Literal["dynamic"]] + + throttle_key: Required[str] + + type: Required[Literal["throttle"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_throttle_static_node.py b/src/courier/types/journey_throttle_static_node.py new file mode 100644 index 00000000..b31ca062 --- /dev/null +++ b/src/courier/types/journey_throttle_static_node.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .journey_conditions_field import JourneyConditionsField + +__all__ = ["JourneyThrottleStaticNode"] + + +class JourneyThrottleStaticNode(BaseModel): + """ + Throttle the journey by a static `scope` (`user` or `global`), allowing at most `max_allowed` invocations per `period`. + """ + + max_allowed: int + + period: str + + scope: Literal["user", "global"] + + type: Literal["throttle"] + + id: Optional[str] = None + + conditions: Optional[JourneyConditionsField] = None + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_throttle_static_node_param.py b/src/courier/types/journey_throttle_static_node_param.py new file mode 100644 index 00000000..780c68a4 --- /dev/null +++ b/src/courier/types/journey_throttle_static_node_param.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .journey_conditions_field_param import JourneyConditionsFieldParam + +__all__ = ["JourneyThrottleStaticNodeParam"] + + +class JourneyThrottleStaticNodeParam(TypedDict, total=False): + """ + Throttle the journey by a static `scope` (`user` or `global`), allowing at most `max_allowed` invocations per `period`. + """ + + max_allowed: Required[int] + + period: Required[str] + + scope: Required[Literal["user", "global"]] + + type: Required[Literal["throttle"]] + + id: str + + conditions: JourneyConditionsFieldParam + """Condition spec for a journey node. + + Accepts a single condition atom, an AND/OR group, or an AND/OR nested group. + Omit the `conditions` property entirely to express "no conditions". + """ diff --git a/src/courier/types/journey_version_item.py b/src/courier/types/journey_version_item.py new file mode 100644 index 00000000..722470da --- /dev/null +++ b/src/courier/types/journey_version_item.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["JourneyVersionItem"] + + +class JourneyVersionItem(BaseModel): + """A published version of a journey.""" + + created: Optional[int] = None + + creator: Optional[str] = None + + name: str + + published: Optional[int] = None + + version: str diff --git a/src/courier/types/journey_versions_list_response.py b/src/courier/types/journey_versions_list_response.py new file mode 100644 index 00000000..ad51098f --- /dev/null +++ b/src/courier/types/journey_versions_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging +from .journey_version_item import JourneyVersionItem + +__all__ = ["JourneyVersionsListResponse"] + + +class JourneyVersionsListResponse(BaseModel): + """Paged list of published journey versions, most recent first.""" + + paging: Paging + + results: List[JourneyVersionItem] diff --git a/src/courier/types/journeys/__init__.py b/src/courier/types/journeys/__init__.py new file mode 100644 index 00000000..969be02c --- /dev/null +++ b/src/courier/types/journeys/__init__.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .template_list_params import TemplateListParams as TemplateListParams +from .template_create_params import TemplateCreateParams as TemplateCreateParams +from .template_publish_params import TemplatePublishParams as TemplatePublishParams +from .template_replace_params import TemplateReplaceParams as TemplateReplaceParams +from .template_put_locale_params import TemplatePutLocaleParams as TemplatePutLocaleParams +from .template_put_content_params import TemplatePutContentParams as TemplatePutContentParams +from .template_retrieve_content_params import TemplateRetrieveContentParams as TemplateRetrieveContentParams diff --git a/src/courier/types/journeys/template_create_params.py b/src/courier/types/journeys/template_create_params.py new file mode 100644 index 00000000..514816d7 --- /dev/null +++ b/src/courier/types/journeys/template_create_params.py @@ -0,0 +1,60 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypedDict + +from ..._types import SequenceNotStr +from ..._utils import PropertyInfo +from ..shared_params.elemental_node import ElementalNode + +__all__ = [ + "TemplateCreateParams", + "Notification", + "NotificationBrand", + "NotificationContent", + "NotificationSubscription", +] + + +class TemplateCreateParams(TypedDict, total=False): + channel: Required[str] + + notification: Required[Notification] + + provider_key: Annotated[str, PropertyInfo(alias="providerKey")] + + state: str + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +class NotificationBrand(TypedDict, total=False): + id: Required[str] + + +class NotificationContent(TypedDict, total=False): + elements: Required[Iterable[ElementalNode]] + + version: Required[Literal["2022-01-01"]] + + scope: Literal["default", "strict"] + + +class NotificationSubscription(TypedDict, total=False): + topic_id: Required[str] + + +class Notification(TypedDict, total=False): + brand: Required[Optional[NotificationBrand]] + + content: Required[NotificationContent] + + name: Required[str] + + subscription: Required[Optional[NotificationSubscription]] + + tags: Required[SequenceNotStr[str]] diff --git a/src/courier/types/journeys/template_list_params.py b/src/courier/types/journeys/template_list_params.py new file mode 100644 index 00000000..3c30e48c --- /dev/null +++ b/src/courier/types/journeys/template_list_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["TemplateListParams"] + + +class TemplateListParams(TypedDict, total=False): + cursor: str + """Pagination cursor from a prior response.""" + + limit: int + """Page size. Minimum 1, maximum 100.""" diff --git a/src/courier/types/journeys/template_publish_params.py b/src/courier/types/journeys/template_publish_params.py new file mode 100644 index 00000000..2c9693e6 --- /dev/null +++ b/src/courier/types/journeys/template_publish_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo + +__all__ = ["TemplatePublishParams"] + + +class TemplatePublishParams(TypedDict, total=False): + template_id: Required[Annotated[str, PropertyInfo(alias="templateId")]] + + version: str + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/journeys/template_put_content_params.py b/src/courier/types/journeys/template_put_content_params.py new file mode 100644 index 00000000..b222c506 --- /dev/null +++ b/src/courier/types/journeys/template_put_content_params.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..notification_template_state import NotificationTemplateState +from ..shared_params.elemental_node import ElementalNode + +__all__ = ["TemplatePutContentParams", "Content"] + + +class TemplatePutContentParams(TypedDict, total=False): + template_id: Required[Annotated[str, PropertyInfo(alias="templateId")]] + + content: Required[Content] + """Elemental content payload. The server defaults `version` when omitted.""" + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" + + +class Content(TypedDict, total=False): + """Elemental content payload. The server defaults `version` when omitted.""" + + elements: Required[Iterable[ElementalNode]] + + version: str + """Content version identifier (e.g., `2022-01-01`). + + Optional; server defaults when omitted. + """ diff --git a/src/courier/types/journeys/template_put_locale_params.py b/src/courier/types/journeys/template_put_locale_params.py new file mode 100644 index 00000000..1c547289 --- /dev/null +++ b/src/courier/types/journeys/template_put_locale_params.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..notification_template_state import NotificationTemplateState + +__all__ = ["TemplatePutLocaleParams", "Element"] + + +class TemplatePutLocaleParams(TypedDict, total=False): + template_id: Required[Annotated[str, PropertyInfo(alias="templateId")]] + + notification_id: Required[Annotated[str, PropertyInfo(alias="notificationId")]] + + elements: Required[Iterable[Element]] + """Elements with locale-specific content overrides.""" + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" + + +class Element( # type: ignore[call-arg] + TypedDict, + total=False, + extra_items=object, # pyright: ignore[reportGeneralTypeIssues] +): + id: Required[str] + """Target element ID.""" diff --git a/src/courier/types/journeys/template_replace_params.py b/src/courier/types/journeys/template_replace_params.py new file mode 100644 index 00000000..a607b37d --- /dev/null +++ b/src/courier/types/journeys/template_replace_params.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypedDict + +from ..._types import SequenceNotStr +from ..._utils import PropertyInfo +from ..shared_params.elemental_node import ElementalNode + +__all__ = [ + "TemplateReplaceParams", + "Notification", + "NotificationBrand", + "NotificationContent", + "NotificationSubscription", +] + + +class TemplateReplaceParams(TypedDict, total=False): + template_id: Required[Annotated[str, PropertyInfo(alias="templateId")]] + + notification: Required[Notification] + + state: str + + +class NotificationBrand(TypedDict, total=False): + id: Required[str] + + +class NotificationContent(TypedDict, total=False): + elements: Required[Iterable[ElementalNode]] + + version: Required[Literal["2022-01-01"]] + + scope: Literal["default", "strict"] + + +class NotificationSubscription(TypedDict, total=False): + topic_id: Required[str] + + +class Notification(TypedDict, total=False): + brand: Required[Optional[NotificationBrand]] + + content: Required[NotificationContent] + + name: Required[str] + + subscription: Required[Optional[NotificationSubscription]] + + tags: Required[SequenceNotStr[str]] diff --git a/src/courier/types/journeys/template_retrieve_content_params.py b/src/courier/types/journeys/template_retrieve_content_params.py new file mode 100644 index 00000000..1264739d --- /dev/null +++ b/src/courier/types/journeys/template_retrieve_content_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo + +__all__ = ["TemplateRetrieveContentParams"] + + +class TemplateRetrieveContentParams(TypedDict, total=False): + template_id: Required[Annotated[str, PropertyInfo(alias="templateId")]] + + version: str + """Accepts `draft`, `published`, or a version string (e.g., `v001`). + + Defaults to `published`. + """ diff --git a/src/courier/types/journeys_invoke_response.py b/src/courier/types/journeys_invoke_response.py new file mode 100644 index 00000000..300c6fa4 --- /dev/null +++ b/src/courier/types/journeys_invoke_response.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["JourneysInvokeResponse"] + + +class JourneysInvokeResponse(BaseModel): + run_id: str = FieldInfo(alias="runId") + """A unique identifier for the journey run that was created.""" diff --git a/src/courier/types/journeys_list_response.py b/src/courier/types/journeys_list_response.py new file mode 100644 index 00000000..c91bf778 --- /dev/null +++ b/src/courier/types/journeys_list_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .journey import Journey +from .._models import BaseModel + +__all__ = ["JourneysListResponse"] + + +class JourneysListResponse(BaseModel): + cursor: Optional[str] = None + """A cursor token for pagination. Present when there are more results available.""" + + templates: Optional[List[Journey]] = None diff --git a/src/courier/types/list_list_params.py b/src/courier/types/list_list_params.py new file mode 100644 index 00000000..91932345 --- /dev/null +++ b/src/courier/types/list_list_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["ListListParams"] + + +class ListListParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next page of lists.""" + + pattern: Optional[str] + """\"A pattern used to filter the list items returned. + + Pattern types supported: exact match on `list_id` or a pattern of one or more + pattern parts. you may replace a part with either: `*` to match all parts in + that position, or `**` to signify a wildcard `endsWith` pattern match." + """ diff --git a/src/courier/types/list_list_response.py b/src/courier/types/list_list_response.py new file mode 100644 index 00000000..16efe415 --- /dev/null +++ b/src/courier/types/list_list_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging +from .subscription_list import SubscriptionList + +__all__ = ["ListListResponse"] + + +class ListListResponse(BaseModel): + items: List[SubscriptionList] + + paging: Paging diff --git a/src/courier/types/list_update_params.py b/src/courier/types/list_update_params.py new file mode 100644 index 00000000..100d8382 --- /dev/null +++ b/src/courier/types/list_update_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from .shared_params.recipient_preferences import RecipientPreferences + +__all__ = ["ListUpdateParams"] + + +class ListUpdateParams(TypedDict, total=False): + name: Required[str] + + preferences: Optional[RecipientPreferences] diff --git a/src/courier/types/lists/__init__.py b/src/courier/types/lists/__init__.py new file mode 100644 index 00000000..97c7000c --- /dev/null +++ b/src/courier/types/lists/__init__.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .subscription_add_params import SubscriptionAddParams as SubscriptionAddParams +from .subscription_list_params import SubscriptionListParams as SubscriptionListParams +from .subscription_list_response import SubscriptionListResponse as SubscriptionListResponse +from .subscription_subscribe_params import SubscriptionSubscribeParams as SubscriptionSubscribeParams +from .subscription_subscribe_user_params import SubscriptionSubscribeUserParams as SubscriptionSubscribeUserParams diff --git a/src/courier/types/lists/subscription_add_params.py b/src/courier/types/lists/subscription_add_params.py new file mode 100644 index 00000000..46d79bbd --- /dev/null +++ b/src/courier/types/lists/subscription_add_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..put_subscriptions_recipient_param import PutSubscriptionsRecipientParam + +__all__ = ["SubscriptionAddParams"] + + +class SubscriptionAddParams(TypedDict, total=False): + recipients: Required[Iterable[PutSubscriptionsRecipientParam]] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/lists/subscription_list_params.py b/src/courier/types/lists/subscription_list_params.py new file mode 100644 index 00000000..9395ff75 --- /dev/null +++ b/src/courier/types/lists/subscription_list_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["SubscriptionListParams"] + + +class SubscriptionListParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of list subscriptions""" diff --git a/src/courier/types/lists/subscription_list_response.py b/src/courier/types/lists/subscription_list_response.py new file mode 100644 index 00000000..13ff31d2 --- /dev/null +++ b/src/courier/types/lists/subscription_list_response.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from pydantic import Field as FieldInfo + +from ..._models import BaseModel +from ..shared.paging import Paging +from ..shared.recipient_preferences import RecipientPreferences + +__all__ = ["SubscriptionListResponse", "Item"] + + +class Item(BaseModel): + recipient_id: str = FieldInfo(alias="recipientId") + + created: Optional[str] = None + + preferences: Optional[RecipientPreferences] = None + + +class SubscriptionListResponse(BaseModel): + items: List[Item] + + paging: Paging diff --git a/src/courier/types/lists/subscription_subscribe_params.py b/src/courier/types/lists/subscription_subscribe_params.py new file mode 100644 index 00000000..93e4ff00 --- /dev/null +++ b/src/courier/types/lists/subscription_subscribe_params.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from ..put_subscriptions_recipient_param import PutSubscriptionsRecipientParam + +__all__ = ["SubscriptionSubscribeParams"] + + +class SubscriptionSubscribeParams(TypedDict, total=False): + recipients: Required[Iterable[PutSubscriptionsRecipientParam]] diff --git a/src/courier/types/lists/subscription_subscribe_user_params.py b/src/courier/types/lists/subscription_subscribe_user_params.py new file mode 100644 index 00000000..d94348de --- /dev/null +++ b/src/courier/types/lists/subscription_subscribe_user_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from ..shared_params.recipient_preferences import RecipientPreferences + +__all__ = ["SubscriptionSubscribeUserParams"] + + +class SubscriptionSubscribeUserParams(TypedDict, total=False): + list_id: Required[str] + + preferences: Optional[RecipientPreferences] diff --git a/src/courier/types/logo.py b/src/courier/types/logo.py new file mode 100644 index 00000000..9a545f67 --- /dev/null +++ b/src/courier/types/logo.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["Logo"] + + +class Logo(BaseModel): + href: Optional[str] = None + + image: Optional[str] = None diff --git a/src/courier/types/logo_param.py b/src/courier/types/logo_param.py new file mode 100644 index 00000000..c5564dcf --- /dev/null +++ b/src/courier/types/logo_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["LogoParam"] + + +class LogoParam(TypedDict, total=False): + href: Optional[str] + + image: Optional[str] diff --git a/src/courier/types/message_content_response.py b/src/courier/types/message_content_response.py new file mode 100644 index 00000000..5e7f49d0 --- /dev/null +++ b/src/courier/types/message_content_response.py @@ -0,0 +1,53 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel + +__all__ = ["MessageContentResponse", "Result", "ResultContent", "ResultContentBlock"] + + +class ResultContentBlock(BaseModel): + text: str + """The block text of the rendered message block.""" + + type: str + """The block type of the rendered message block.""" + + +class ResultContent(BaseModel): + """Content details of the rendered message.""" + + blocks: List[ResultContentBlock] + """The blocks of the rendered message.""" + + body: str + """The body of the rendered message.""" + + html: str + """The html content of the rendered message.""" + + subject: str + """The subject of the rendered message.""" + + text: str + """The text of the rendered message.""" + + title: str + """The title of the rendered message.""" + + +class Result(BaseModel): + channel: str + """The channel used for rendering the message.""" + + channel_id: str + """The ID of channel used for rendering the message.""" + + content: ResultContent + """Content details of the rendered message.""" + + +class MessageContentResponse(BaseModel): + results: List[Result] + """An array of render output of a previously sent message.""" diff --git a/src/courier/types/message_details.py b/src/courier/types/message_details.py new file mode 100644 index 00000000..4564f9d4 --- /dev/null +++ b/src/courier/types/message_details.py @@ -0,0 +1,92 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["MessageDetails"] + + +class MessageDetails(BaseModel): + id: str + """ + A unique identifier associated with the message you wish to retrieve (results + from a send). + """ + + enqueued: int + """A UTC timestamp at which Courier received the message request. + + Stored as a millisecond representation of the Unix epoch. + """ + + event: str + """A unique identifier associated with the event of the delivered message.""" + + notification: str + """A unique identifier associated with the notification of the delivered message.""" + + recipient: str + """A unique identifier associated with the recipient of the delivered message.""" + + status: Literal[ + "CANCELED", + "CLICKED", + "DELAYED", + "DELIVERED", + "DIGESTED", + "ENQUEUED", + "FILTERED", + "OPENED", + "ROUTED", + "SENT", + "SIMULATED", + "THROTTLED", + "UNDELIVERABLE", + "UNMAPPED", + "UNROUTABLE", + ] + """The current status of the message.""" + + clicked: Optional[int] = None + """ + A UTC timestamp at which the recipient clicked on a tracked link for the first + time. Stored as a millisecond representation of the Unix epoch. + """ + + delivered: Optional[int] = None + """A UTC timestamp at which the Integration provider delivered the message. + + Stored as a millisecond representation of the Unix epoch. + """ + + error: Optional[str] = None + """A message describing the error that occurred.""" + + opened: Optional[int] = None + """A UTC timestamp at which the recipient opened a message for the first time. + + Stored as a millisecond representation of the Unix epoch. + """ + + reason: Optional[ + Literal[ + "BOUNCED", + "FAILED", + "FILTERED", + "NO_CHANNELS", + "NO_PROVIDERS", + "OPT_IN_REQUIRED", + "PROVIDER_ERROR", + "UNPUBLISHED", + "UNSUBSCRIBED", + ] + ] = None + """The reason for the current status of the message.""" + + sent: Optional[int] = None + """A UTC timestamp at which Courier passed the message to the Integration provider. + + Stored as a millisecond representation of the Unix epoch. + """ diff --git a/src/courier/types/message_history_params.py b/src/courier/types/message_history_params.py new file mode 100644 index 00000000..67978cc5 --- /dev/null +++ b/src/courier/types/message_history_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["MessageHistoryParams"] + + +class MessageHistoryParams(TypedDict, total=False): + type: Optional[str] + """A supported Message History type that will filter the events returned.""" diff --git a/src/courier/types/message_history_response.py b/src/courier/types/message_history_response.py new file mode 100644 index 00000000..a1bcde62 --- /dev/null +++ b/src/courier/types/message_history_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List + +from .._models import BaseModel + +__all__ = ["MessageHistoryResponse"] + + +class MessageHistoryResponse(BaseModel): + results: List[Dict[str, object]] diff --git a/src/courier/types/message_list_params.py b/src/courier/types/message_list_params.py new file mode 100644 index 00000000..543a8a23 --- /dev/null +++ b/src/courier/types/message_list_params.py @@ -0,0 +1,80 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Annotated, TypedDict + +from .._types import SequenceNotStr +from .._utils import PropertyInfo + +__all__ = ["MessageListParams"] + + +class MessageListParams(TypedDict, total=False): + archived: Optional[bool] + """ + A boolean value that indicates whether archived messages should be included in + the response. + """ + + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of messages.""" + + enqueued_after: Optional[str] + """The enqueued datetime of a message to filter out messages received before.""" + + event: Optional[str] + """A unique identifier representing the event that was used to send the event.""" + + list: Optional[str] + """A unique identifier representing the list the message was sent to.""" + + message_id: Annotated[Optional[str], PropertyInfo(alias="messageId")] + """ + A unique identifier representing the message_id returned from either /send or + /send/list. + """ + + notification: Optional[str] + """ + A unique identifier representing the notification that was used to send the + event. + """ + + provider: SequenceNotStr[Optional[str]] + """The key assocated to the provider you want to filter on. + + E.g., sendgrid, inbox, twilio, slack, msteams, etc. Allows multiple values to be + set in query parameters. + """ + + recipient: Optional[str] + """ + A unique identifier representing the recipient associated with the requested + profile. + """ + + status: SequenceNotStr[Optional[str]] + """An indicator of the current status of the message. + + Allows multiple values to be set in query parameters. + """ + + tag: SequenceNotStr[Optional[str]] + """A tag placed in the metadata.tags during a notification send. + + Allows multiple values to be set in query parameters. + """ + + tags: Optional[str] + """A comma delimited list of 'tags'. + + Messages will be returned if they match any of the tags passed in. + """ + + tenant_id: Optional[str] + """Messages sent with the context of a Tenant""" + + trace_id: Annotated[Optional[str], PropertyInfo(alias="traceId")] + """The unique identifier used to trace the requests""" diff --git a/src/courier/types/message_list_response.py b/src/courier/types/message_list_response.py new file mode 100644 index 00000000..1a004ecd --- /dev/null +++ b/src/courier/types/message_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging +from .message_details import MessageDetails + +__all__ = ["MessageListResponse"] + + +class MessageListResponse(BaseModel): + paging: Paging + """Paging information for the result set.""" + + results: List[MessageDetails] + """An array of messages with their details.""" diff --git a/src/courier/types/message_resend_response.py b/src/courier/types/message_resend_response.py new file mode 100644 index 00000000..e4691839 --- /dev/null +++ b/src/courier/types/message_resend_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["MessageResendResponse"] + + +class MessageResendResponse(BaseModel): + message_id: str = FieldInfo(alias="messageId") + """The new message id for the resent message. + + It is distinct from the id of the original message that was resent. + """ diff --git a/src/courier/types/message_retrieve_response.py b/src/courier/types/message_retrieve_response.py new file mode 100644 index 00000000..06a92fef --- /dev/null +++ b/src/courier/types/message_retrieve_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional + +from .message_details import MessageDetails + +__all__ = ["MessageRetrieveResponse"] + + +class MessageRetrieveResponse(MessageDetails): + providers: Optional[List[Dict[str, object]]] = None diff --git a/src/courier/types/notification_content_get_response.py b/src/courier/types/notification_content_get_response.py new file mode 100644 index 00000000..95634845 --- /dev/null +++ b/src/courier/types/notification_content_get_response.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List + +from .._models import BaseModel + +__all__ = ["NotificationContentGetResponse"] + + +class NotificationContentGetResponse(BaseModel): + """Elemental content response for V2 templates. + + Contains versioned elements with content checksums. + """ + + elements: List["ElementWithChecksums"] + + version: str + """Content version identifier.""" + + +from .element_with_checksums import ElementWithChecksums diff --git a/src/courier/types/notification_content_mutation_response.py b/src/courier/types/notification_content_mutation_response.py new file mode 100644 index 00000000..94130ac9 --- /dev/null +++ b/src/courier/types/notification_content_mutation_response.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .notification_template_state import NotificationTemplateState + +__all__ = ["NotificationContentMutationResponse", "Element"] + + +class Element(BaseModel): + id: str + + checksum: str + + +class NotificationContentMutationResponse(BaseModel): + """ + Shared mutation response for `PUT` content, `PUT` element, and `PUT` locale operations. Contains the template ID, content version, per-element checksums, and resulting state. + """ + + id: str + """Template ID.""" + + elements: List[Element] + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" + + version: str + """Content version identifier.""" diff --git a/src/courier/types/notification_create_params.py b/src/courier/types/notification_create_params.py new file mode 100644 index 00000000..819da0ef --- /dev/null +++ b/src/courier/types/notification_create_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .notification_template_write_payload_param import NotificationTemplateWritePayloadParam + +__all__ = ["NotificationCreateParams"] + + +class NotificationCreateParams(TypedDict, total=False): + notification: Required[NotificationTemplateWritePayloadParam] + """ + Template fields accepted in POST and PUT request bodies, nested under a + `notification` key. + """ + + state: Literal["DRAFT", "PUBLISHED"] + """Template state after creation. + + Case-insensitive input, normalized to uppercase in the response. Defaults to + "DRAFT". + """ + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/notification_get_content.py b/src/courier/types/notification_get_content.py new file mode 100644 index 00000000..0bec3fed --- /dev/null +++ b/src/courier/types/notification_get_content.py @@ -0,0 +1,84 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, TypeAlias + +from .._models import BaseModel + +__all__ = [ + "NotificationGetContent", + "Block", + "BlockContent", + "BlockContentNotificationContentHierarchy", + "BlockLocales", + "BlockLocalesNotificationContentHierarchy", + "Channel", + "ChannelContent", + "ChannelLocales", +] + + +class BlockContentNotificationContentHierarchy(BaseModel): + children: Optional[str] = None + + parent: Optional[str] = None + + +BlockContent: TypeAlias = Union[str, BlockContentNotificationContentHierarchy, None] + + +class BlockLocalesNotificationContentHierarchy(BaseModel): + children: Optional[str] = None + + parent: Optional[str] = None + + +BlockLocales: TypeAlias = Union[str, BlockLocalesNotificationContentHierarchy] + + +class Block(BaseModel): + id: str + + type: Literal["action", "divider", "image", "jsonnet", "list", "markdown", "quote", "template", "text"] + + alias: Optional[str] = None + + checksum: Optional[str] = None + + content: Optional[BlockContent] = None + + context: Optional[str] = None + + locales: Optional[Dict[str, BlockLocales]] = None + + +class ChannelContent(BaseModel): + subject: Optional[str] = None + + title: Optional[str] = None + + +class ChannelLocales(BaseModel): + subject: Optional[str] = None + + title: Optional[str] = None + + +class Channel(BaseModel): + id: str + + checksum: Optional[str] = None + + content: Optional[ChannelContent] = None + + locales: Optional[Dict[str, ChannelLocales]] = None + + type: Optional[str] = None + + +class NotificationGetContent(BaseModel): + blocks: Optional[List[Block]] = None + + channels: Optional[List[Channel]] = None + + checksum: Optional[str] = None diff --git a/src/courier/types/notification_list_params.py b/src/courier/types/notification_list_params.py new file mode 100644 index 00000000..26106e9a --- /dev/null +++ b/src/courier/types/notification_list_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["NotificationListParams"] + + +class NotificationListParams(TypedDict, total=False): + cursor: Optional[str] + """Opaque pagination cursor from a previous response. Omit for the first page.""" + + event_id: str + """Filter to templates linked to this event map ID.""" + + notes: Optional[bool] + """Include template notes in the response. Only applies to legacy templates.""" diff --git a/src/courier/types/notification_list_response.py b/src/courier/types/notification_list_response.py new file mode 100644 index 00000000..1be59f74 --- /dev/null +++ b/src/courier/types/notification_list_response.py @@ -0,0 +1,62 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Optional +from typing_extensions import TypeAlias + +from .._models import BaseModel +from .shared.paging import Paging +from .notification_template_summary import NotificationTemplateSummary + +__all__ = [ + "NotificationListResponse", + "Result", + "ResultNotification", + "ResultNotificationTags", + "ResultNotificationTagsData", +] + + +class ResultNotificationTagsData(BaseModel): + id: str + + name: str + + +class ResultNotificationTags(BaseModel): + data: List[ResultNotificationTagsData] + + +class ResultNotification(BaseModel): + id: str + + created_at: int + + event_ids: List[str] + """Array of event IDs associated with this notification""" + + routing: "MessageRouting" + + topic_id: str + + updated_at: int + + note: Optional[str] = None + + tags: Optional[ResultNotificationTags] = None + + title: Optional[str] = None + + +Result: TypeAlias = Union[ResultNotification, NotificationTemplateSummary] + + +class NotificationListResponse(BaseModel): + paging: Paging + + results: List[Result] + """Notification templates in this workspace.""" + + +from .shared.message_routing import MessageRouting diff --git a/src/courier/types/notification_list_versions_params.py b/src/courier/types/notification_list_versions_params.py new file mode 100644 index 00000000..64c9c466 --- /dev/null +++ b/src/courier/types/notification_list_versions_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["NotificationListVersionsParams"] + + +class NotificationListVersionsParams(TypedDict, total=False): + cursor: str + """Opaque pagination cursor from a previous response. Omit for the first page.""" + + limit: int + """Maximum number of versions to return per page. Default 10, max 10.""" diff --git a/src/courier/types/notification_publish_params.py b/src/courier/types/notification_publish_params.py new file mode 100644 index 00000000..b5945921 --- /dev/null +++ b/src/courier/types/notification_publish_params.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["NotificationPublishParams"] + + +class NotificationPublishParams(TypedDict, total=False): + version: str + """Historical version to publish (e.g. "v001"). Omit to publish the current draft.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/notification_put_content_params.py b/src/courier/types/notification_put_content_params.py new file mode 100644 index 00000000..5f2764d0 --- /dev/null +++ b/src/courier/types/notification_put_content_params.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from .notification_template_state import NotificationTemplateState +from .shared_params.elemental_node import ElementalNode + +__all__ = ["NotificationPutContentParams", "Content"] + + +class NotificationPutContentParams(TypedDict, total=False): + content: Required[Content] + """Elemental content payload. The server defaults `version` when omitted.""" + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" + + +class Content(TypedDict, total=False): + """Elemental content payload. The server defaults `version` when omitted.""" + + elements: Required[Iterable[ElementalNode]] + + version: str + """Content version identifier (e.g., `2022-01-01`). + + Optional; server defaults when omitted. + """ diff --git a/src/courier/types/notification_put_element_params.py b/src/courier/types/notification_put_element_params.py new file mode 100644 index 00000000..2cf28c71 --- /dev/null +++ b/src/courier/types/notification_put_element_params.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, Annotated, TypedDict + +from .._types import SequenceNotStr +from .._utils import PropertyInfo +from .notification_template_state import NotificationTemplateState + +__all__ = ["NotificationPutElementParams"] + + +class NotificationPutElementParams(TypedDict, total=False): + id: Required[str] + + type: Required[str] + """Element type (text, meta, action, image, etc.).""" + + channels: SequenceNotStr[str] + + data: Dict[str, object] + + if_: Annotated[str, PropertyInfo(alias="if")] + + loop: str + + ref: str + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" diff --git a/src/courier/types/notification_put_locale_params.py b/src/courier/types/notification_put_locale_params.py new file mode 100644 index 00000000..6b714492 --- /dev/null +++ b/src/courier/types/notification_put_locale_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from .notification_template_state import NotificationTemplateState + +__all__ = ["NotificationPutLocaleParams", "Element"] + + +class NotificationPutLocaleParams(TypedDict, total=False): + id: Required[str] + + elements: Required[Iterable[Element]] + """Elements with locale-specific content overrides.""" + + state: NotificationTemplateState + """Template state. Defaults to `DRAFT`.""" + + +class Element( # type: ignore[call-arg] + TypedDict, + total=False, + extra_items=object, # pyright: ignore[reportGeneralTypeIssues] +): + id: Required[str] + """Target element ID.""" diff --git a/src/courier/types/notification_replace_params.py b/src/courier/types/notification_replace_params.py new file mode 100644 index 00000000..e74cf13d --- /dev/null +++ b/src/courier/types/notification_replace_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .notification_template_write_payload_param import NotificationTemplateWritePayloadParam + +__all__ = ["NotificationReplaceParams"] + + +class NotificationReplaceParams(TypedDict, total=False): + notification: Required[NotificationTemplateWritePayloadParam] + """ + Template fields accepted in POST and PUT request bodies, nested under a + `notification` key. + """ + + state: Literal["DRAFT", "PUBLISHED"] + """Template state after update. + + Case-insensitive input, normalized to uppercase in the response. Defaults to + "DRAFT". + """ diff --git a/src/courier/types/notification_retrieve_content_params.py b/src/courier/types/notification_retrieve_content_params.py new file mode 100644 index 00000000..a3096fec --- /dev/null +++ b/src/courier/types/notification_retrieve_content_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["NotificationRetrieveContentParams"] + + +class NotificationRetrieveContentParams(TypedDict, total=False): + version: str + """Accepts `draft`, `published`, or a version string (e.g., `v001`). + + Defaults to `published`. + """ diff --git a/src/courier/types/notification_retrieve_content_response.py b/src/courier/types/notification_retrieve_content_response.py new file mode 100644 index 00000000..23e1df32 --- /dev/null +++ b/src/courier/types/notification_retrieve_content_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .notification_get_content import NotificationGetContent + +__all__ = ["NotificationRetrieveContentResponse"] + +NotificationRetrieveContentResponse: TypeAlias = Union["NotificationContentGetResponse", NotificationGetContent] + +from .notification_content_get_response import NotificationContentGetResponse diff --git a/src/courier/types/notification_retrieve_params.py b/src/courier/types/notification_retrieve_params.py new file mode 100644 index 00000000..78e933aa --- /dev/null +++ b/src/courier/types/notification_retrieve_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["NotificationRetrieveParams"] + + +class NotificationRetrieveParams(TypedDict, total=False): + version: str + """Version to retrieve. + + One of "draft", "published", or a version string like "v001". Defaults to + "published". + """ diff --git a/src/courier/types/notification_template_alias.py b/src/courier/types/notification_template_alias.py new file mode 100644 index 00000000..3b05b39f --- /dev/null +++ b/src/courier/types/notification_template_alias.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import TypeAlias + +__all__ = ["NotificationTemplateAlias"] + +NotificationTemplateAlias: TypeAlias = Union[str, List[str]] diff --git a/src/courier/types/notification_template_payload.py b/src/courier/types/notification_template_payload.py new file mode 100644 index 00000000..379534bb --- /dev/null +++ b/src/courier/types/notification_template_payload.py @@ -0,0 +1,50 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel +from .shared.elemental_content import ElementalContent + +__all__ = ["NotificationTemplatePayload", "Brand", "Routing", "Subscription"] + + +class Brand(BaseModel): + """Brand reference, or null for no brand.""" + + id: str + + +class Routing(BaseModel): + """Routing strategy reference, or null for none.""" + + strategy_id: str + + +class Subscription(BaseModel): + """Subscription topic reference, or null for none.""" + + topic_id: str + + +class NotificationTemplatePayload(BaseModel): + """ + Core template fields used in POST and PUT request bodies (nested under a `notification` key) and returned at the top level in responses. + """ + + brand: Optional[Brand] = None + """Brand reference, or null for no brand.""" + + content: ElementalContent + """Elemental content definition.""" + + name: str + """Display name for the template.""" + + routing: Optional[Routing] = None + """Routing strategy reference, or null for none.""" + + subscription: Optional[Subscription] = None + """Subscription topic reference, or null for none.""" + + tags: List[str] + """Tags for categorization. Send empty array for none.""" diff --git a/src/courier/types/notification_template_payload_param.py b/src/courier/types/notification_template_payload_param.py new file mode 100644 index 00000000..52f321d6 --- /dev/null +++ b/src/courier/types/notification_template_payload_param.py @@ -0,0 +1,53 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from .._types import SequenceNotStr +from .shared_params.elemental_content import ElementalContent + +__all__ = ["NotificationTemplatePayloadParam", "Brand", "Routing", "Subscription"] + + +class Brand(TypedDict, total=False): + """Brand reference, or null for no brand.""" + + id: Required[str] + + +class Routing(TypedDict, total=False): + """Routing strategy reference, or null for none.""" + + strategy_id: Required[str] + + +class Subscription(TypedDict, total=False): + """Subscription topic reference, or null for none.""" + + topic_id: Required[str] + + +class NotificationTemplatePayloadParam(TypedDict, total=False): + """ + Core template fields used in POST and PUT request bodies (nested under a `notification` key) and returned at the top level in responses. + """ + + brand: Required[Optional[Brand]] + """Brand reference, or null for no brand.""" + + content: Required[ElementalContent] + """Elemental content definition.""" + + name: Required[str] + """Display name for the template.""" + + routing: Required[Optional[Routing]] + """Routing strategy reference, or null for none.""" + + subscription: Required[Optional[Subscription]] + """Subscription topic reference, or null for none.""" + + tags: Required[SequenceNotStr[str]] + """Tags for categorization. Send empty array for none.""" diff --git a/src/courier/types/notification_template_response.py b/src/courier/types/notification_template_response.py new file mode 100644 index 00000000..0e4f8a02 --- /dev/null +++ b/src/courier/types/notification_template_response.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .notification_template_alias import NotificationTemplateAlias +from .notification_template_payload import NotificationTemplatePayload + +__all__ = ["NotificationTemplateResponse"] + + +class NotificationTemplateResponse(NotificationTemplatePayload): + """ + Response for GET /notifications/{id}, POST /notifications, and PUT /notifications/{id}. Returns all template fields at the top level. + """ + + id: str + """The template ID.""" + + created: int + """Epoch milliseconds when the template was created.""" + + creator: str + """User ID of the creator.""" + + state: Literal["DRAFT", "PUBLISHED"] + """The template state. Always uppercase.""" + + alias: Optional[NotificationTemplateAlias] = None + """ + A template's send-time alias as returned by a read, omitted entirely when it has + none. Usually a single string; an array for a template that resolves from + several aliases, which writes through this API can no longer produce — only + templates predating that restriction, or aliases attached outside this API, hold + more than one. + """ + + updated: Optional[int] = None + """Epoch milliseconds of last update.""" + + updater: Optional[str] = None + """User ID of the last updater.""" diff --git a/src/courier/types/notification_template_state.py b/src/courier/types/notification_template_state.py new file mode 100644 index 00000000..18e06b25 --- /dev/null +++ b/src/courier/types/notification_template_state.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["NotificationTemplateState"] + +NotificationTemplateState: TypeAlias = Literal["DRAFT", "PUBLISHED"] diff --git a/src/courier/types/notification_template_summary.py b/src/courier/types/notification_template_summary.py new file mode 100644 index 00000000..78ab7cc2 --- /dev/null +++ b/src/courier/types/notification_template_summary.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["NotificationTemplateSummary"] + + +class NotificationTemplateSummary(BaseModel): + """V2 (CDS) template summary returned in list responses.""" + + id: str + + created: int + """Epoch milliseconds when the template was created.""" + + creator: str + """User ID of the creator.""" + + name: str + + state: Literal["DRAFT", "PUBLISHED"] + + tags: List[str] + + subscription_topic_id: Optional[str] = None + """The linked subscription (preference) topic of the published version. + + Omitted when no topic is linked or the template has never been published. + """ + + topic_id: Optional[str] = None + """ + Alias of subscription_topic_id, provided under the same name V1 list items use + for the linked topic. Always carries the same value as subscription_topic_id. + """ + + updated: Optional[int] = None + """Epoch milliseconds of last update.""" + + updater: Optional[str] = None + """User ID of the last updater.""" diff --git a/src/courier/types/notification_template_version_list_response.py b/src/courier/types/notification_template_version_list_response.py new file mode 100644 index 00000000..6bc29236 --- /dev/null +++ b/src/courier/types/notification_template_version_list_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .version_node import VersionNode +from .shared.paging import Paging + +__all__ = ["NotificationTemplateVersionListResponse"] + + +class NotificationTemplateVersionListResponse(BaseModel): + paging: Paging + + versions: List[VersionNode] diff --git a/src/courier/types/notification_template_write_payload_param.py b/src/courier/types/notification_template_write_payload_param.py new file mode 100644 index 00000000..f7049760 --- /dev/null +++ b/src/courier/types/notification_template_write_payload_param.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional + +from .notification_template_payload_param import NotificationTemplatePayloadParam + +__all__ = ["NotificationTemplateWritePayloadParam"] + + +class NotificationTemplateWritePayloadParam(NotificationTemplatePayloadParam, total=False): + """ + Template fields accepted in POST and PUT request bodies, nested under a `notification` key. + """ + + alias: Optional[str] + """Send-time alias for this template — the value you pass as `event` to POST /send. + + Writes accept a single alias only. Optional, with three distinct meanings. Omit + it to leave any existing aliases untouched. Send a string to make this the + template's only alias — a template that already resolved from several aliases + keeps just this one and the rest are detached. Send null to remove every alias + from the template. An alias may not be claimed by another template — doing so + returns 409 — and may not begin with "tenant/". + """ diff --git a/src/courier/types/notifications/__init__.py b/src/courier/types/notifications/__init__.py new file mode 100644 index 00000000..c1669214 --- /dev/null +++ b/src/courier/types/notifications/__init__.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .check_list_response import CheckListResponse as CheckListResponse +from .check_update_params import CheckUpdateParams as CheckUpdateParams +from .check_update_response import CheckUpdateResponse as CheckUpdateResponse diff --git a/src/courier/types/notifications/check_list_response.py b/src/courier/types/notifications/check_list_response.py new file mode 100644 index 00000000..b201ed00 --- /dev/null +++ b/src/courier/types/notifications/check_list_response.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..check import Check +from ..._models import BaseModel + +__all__ = ["CheckListResponse"] + + +class CheckListResponse(BaseModel): + checks: List[Check] diff --git a/src/courier/types/notifications/check_update_params.py b/src/courier/types/notifications/check_update_params.py new file mode 100644 index 00000000..7a6c96a0 --- /dev/null +++ b/src/courier/types/notifications/check_update_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from ..base_check_param import BaseCheckParam + +__all__ = ["CheckUpdateParams"] + + +class CheckUpdateParams(TypedDict, total=False): + id: Required[str] + + checks: Required[Iterable[BaseCheckParam]] diff --git a/src/courier/types/notifications/check_update_response.py b/src/courier/types/notifications/check_update_response.py new file mode 100644 index 00000000..99292100 --- /dev/null +++ b/src/courier/types/notifications/check_update_response.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..check import Check +from ..._models import BaseModel + +__all__ = ["CheckUpdateResponse"] + + +class CheckUpdateResponse(BaseModel): + checks: List[Check] diff --git a/src/courier/types/post_tenant_template_publish_response.py b/src/courier/types/post_tenant_template_publish_response.py new file mode 100644 index 00000000..5cc56153 --- /dev/null +++ b/src/courier/types/post_tenant_template_publish_response.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["PostTenantTemplatePublishResponse"] + + +class PostTenantTemplatePublishResponse(BaseModel): + """Response from publishing a tenant template""" + + id: str + """The template ID""" + + published_at: str + """The timestamp when the template was published""" + + version: str + """The published version of the template""" diff --git a/src/courier/types/profile_create_params.py b/src/courier/types/profile_create_params.py new file mode 100644 index 00000000..939ebb1a --- /dev/null +++ b/src/courier/types/profile_create_params.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["ProfileCreateParams"] + + +class ProfileCreateParams(TypedDict, total=False): + profile: Required[Dict[str, object]] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/profile_create_response.py b/src/courier/types/profile_create_response.py new file mode 100644 index 00000000..21e119b4 --- /dev/null +++ b/src/courier/types/profile_create_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ProfileCreateResponse"] + + +class ProfileCreateResponse(BaseModel): + status: Literal["SUCCESS"] diff --git a/src/courier/types/profile_replace_params.py b/src/courier/types/profile_replace_params.py new file mode 100644 index 00000000..c76ec99c --- /dev/null +++ b/src/courier/types/profile_replace_params.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, TypedDict + +__all__ = ["ProfileReplaceParams"] + + +class ProfileReplaceParams(TypedDict, total=False): + profile: Required[Dict[str, object]] diff --git a/src/courier/types/profile_replace_response.py b/src/courier/types/profile_replace_response.py new file mode 100644 index 00000000..43f90323 --- /dev/null +++ b/src/courier/types/profile_replace_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ProfileReplaceResponse"] + + +class ProfileReplaceResponse(BaseModel): + status: Literal["SUCCESS"] diff --git a/src/courier/types/profile_retrieve_response.py b/src/courier/types/profile_retrieve_response.py new file mode 100644 index 00000000..c10678c2 --- /dev/null +++ b/src/courier/types/profile_retrieve_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .._models import BaseModel +from .shared.recipient_preferences import RecipientPreferences + +__all__ = ["ProfileRetrieveResponse"] + + +class ProfileRetrieveResponse(BaseModel): + profile: Dict[str, object] + + preferences: Optional[RecipientPreferences] = None diff --git a/src/courier/types/profile_update_params.py b/src/courier/types/profile_update_params.py new file mode 100644 index 00000000..09c8e41c --- /dev/null +++ b/src/courier/types/profile_update_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +__all__ = ["ProfileUpdateParams", "Patch"] + + +class ProfileUpdateParams(TypedDict, total=False): + patch: Required[Iterable[Patch]] + """List of patch operations to apply to the profile.""" + + +class Patch(TypedDict, total=False): + op: Required[str] + """The operation to perform.""" + + path: Required[str] + """The JSON path specifying the part of the profile to operate on.""" + + value: Required[str] + """The value for the operation.""" diff --git a/src/courier/types/profiles/__init__.py b/src/courier/types/profiles/__init__.py new file mode 100644 index 00000000..fe52bdb9 --- /dev/null +++ b/src/courier/types/profiles/__init__.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .list_delete_response import ListDeleteResponse as ListDeleteResponse +from .list_retrieve_params import ListRetrieveParams as ListRetrieveParams +from .list_subscribe_params import ListSubscribeParams as ListSubscribeParams +from .list_retrieve_response import ListRetrieveResponse as ListRetrieveResponse +from .list_subscribe_response import ListSubscribeResponse as ListSubscribeResponse diff --git a/src/courier/types/profiles/list_delete_response.py b/src/courier/types/profiles/list_delete_response.py new file mode 100644 index 00000000..2bb39a8c --- /dev/null +++ b/src/courier/types/profiles/list_delete_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ListDeleteResponse"] + + +class ListDeleteResponse(BaseModel): + status: Literal["SUCCESS"] diff --git a/src/courier/types/profiles/list_retrieve_params.py b/src/courier/types/profiles/list_retrieve_params.py new file mode 100644 index 00000000..b0f3ceb3 --- /dev/null +++ b/src/courier/types/profiles/list_retrieve_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["ListRetrieveParams"] + + +class ListRetrieveParams(TypedDict, total=False): + cursor: Optional[str] + """A unique identifier that allows for fetching the next set of message statuses.""" diff --git a/src/courier/types/profiles/list_retrieve_response.py b/src/courier/types/profiles/list_retrieve_response.py new file mode 100644 index 00000000..4d03eccf --- /dev/null +++ b/src/courier/types/profiles/list_retrieve_response.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from ..._models import BaseModel +from ..shared.paging import Paging +from ..shared.recipient_preferences import RecipientPreferences + +__all__ = ["ListRetrieveResponse", "Result"] + + +class Result(BaseModel): + id: str + + created: str + """The date/time of when the list was created. + + Represented as a string in ISO format. + """ + + name: str + """List name""" + + updated: str + """The date/time of when the list was updated. + + Represented as a string in ISO format. + """ + + preferences: Optional[RecipientPreferences] = None + + +class ListRetrieveResponse(BaseModel): + paging: Paging + + results: List[Result] + """An array of lists""" diff --git a/src/courier/types/profiles/list_subscribe_params.py b/src/courier/types/profiles/list_subscribe_params.py new file mode 100644 index 00000000..2251c365 --- /dev/null +++ b/src/courier/types/profiles/list_subscribe_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..subscribe_to_lists_request_item_param import SubscribeToListsRequestItemParam + +__all__ = ["ListSubscribeParams"] + + +class ListSubscribeParams(TypedDict, total=False): + lists: Required[Iterable[SubscribeToListsRequestItemParam]] + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/profiles/list_subscribe_response.py b/src/courier/types/profiles/list_subscribe_response.py new file mode 100644 index 00000000..301496dc --- /dev/null +++ b/src/courier/types/profiles/list_subscribe_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ListSubscribeResponse"] + + +class ListSubscribeResponse(BaseModel): + status: Literal["SUCCESS"] diff --git a/src/courier/types/provider.py b/src/courier/types/provider.py new file mode 100644 index 00000000..e20128b2 --- /dev/null +++ b/src/courier/types/provider.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .._models import BaseModel + +__all__ = ["Provider"] + + +class Provider(BaseModel): + """A configured provider in the workspace.""" + + id: str + """A unique identifier for the provider configuration.""" + + created: int + """Unix timestamp (ms) of when the provider was created.""" + + provider: str + """The provider key (e.g. "sendgrid", "twilio", "slack").""" + + settings: Dict[str, object] + """Provider-specific settings (snake_case keys on the wire).""" + + title: str + """Display title. Defaults to "Default Configuration" when not explicitly set.""" + + alias: Optional[str] = None + """Optional alias for this configuration.""" + + updated: Optional[int] = None + """Unix timestamp (ms) of when the provider was last updated.""" diff --git a/src/courier/types/provider_create_params.py b/src/courier/types/provider_create_params.py new file mode 100644 index 00000000..687be93f --- /dev/null +++ b/src/courier/types/provider_create_params.py @@ -0,0 +1,37 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["ProviderCreateParams"] + + +class ProviderCreateParams(TypedDict, total=False): + provider: Required[str] + """The provider key identifying the type (e.g. + + "sendgrid", "twilio"). Must be a known Courier provider — see the catalog + endpoint for valid keys. + """ + + alias: str + """Optional alias for this configuration.""" + + settings: Dict[str, object] + """Provider-specific settings (snake_case keys). + + Defaults to an empty object when omitted. Use the catalog endpoint to discover + required fields for a given provider — omitting a required field returns a 400 + validation error. + """ + + title: str + """Optional display title. Omit to use "Default Configuration".""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/provider_list_params.py b/src/courier/types/provider_list_params.py new file mode 100644 index 00000000..9b3026ba --- /dev/null +++ b/src/courier/types/provider_list_params.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ProviderListParams"] + + +class ProviderListParams(TypedDict, total=False): + cursor: str + """Opaque cursor for fetching the next page.""" diff --git a/src/courier/types/provider_list_response.py b/src/courier/types/provider_list_response.py new file mode 100644 index 00000000..0f04f78a --- /dev/null +++ b/src/courier/types/provider_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .provider import Provider +from .shared.paging import Paging + +__all__ = ["ProviderListResponse"] + + +class ProviderListResponse(BaseModel): + """Paginated list of provider configurations.""" + + paging: Paging + + results: List[Provider] diff --git a/src/courier/types/provider_update_params.py b/src/courier/types/provider_update_params.py new file mode 100644 index 00000000..20699f9d --- /dev/null +++ b/src/courier/types/provider_update_params.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Required, TypedDict + +__all__ = ["ProviderUpdateParams"] + + +class ProviderUpdateParams(TypedDict, total=False): + provider: Required[str] + """The provider key identifying the type. + + Required on every request because it selects the provider-specific settings + schema for validation. + """ + + alias: str + """Updated alias. Omit to clear.""" + + settings: Dict[str, object] + """Provider-specific settings (snake_case keys). + + Replaces the full settings object — omitted settings fields are removed. Use the + catalog endpoint to check required fields. + """ + + title: str + """Updated display title.""" diff --git a/src/courier/types/providers/__init__.py b/src/courier/types/providers/__init__.py new file mode 100644 index 00000000..06c79b34 --- /dev/null +++ b/src/courier/types/providers/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .catalog_list_params import CatalogListParams as CatalogListParams +from .catalog_list_response import CatalogListResponse as CatalogListResponse diff --git a/src/courier/types/providers/catalog_list_params.py b/src/courier/types/providers/catalog_list_params.py new file mode 100644 index 00000000..b57f09b4 --- /dev/null +++ b/src/courier/types/providers/catalog_list_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["CatalogListParams"] + + +class CatalogListParams(TypedDict, total=False): + channel: str + """Exact match (case-insensitive) against the provider channel taxonomy (e.g. + + `email`, `sms`, `push`). + """ + + keys: str + """Comma-separated provider keys to filter by (e.g. `sendgrid,twilio`).""" + + name: str + """Case-insensitive substring match against the provider display name.""" diff --git a/src/courier/types/providers/catalog_list_response.py b/src/courier/types/providers/catalog_list_response.py new file mode 100644 index 00000000..475e9395 --- /dev/null +++ b/src/courier/types/providers/catalog_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from ..shared.paging import Paging +from ..providers_catalog_entry import ProvidersCatalogEntry + +__all__ = ["CatalogListResponse"] + + +class CatalogListResponse(BaseModel): + """Paginated list of available provider types with their configuration schemas.""" + + paging: Paging + + results: List[ProvidersCatalogEntry] diff --git a/src/courier/types/providers_catalog_entry.py b/src/courier/types/providers_catalog_entry.py new file mode 100644 index 00000000..950cf66e --- /dev/null +++ b/src/courier/types/providers_catalog_entry.py @@ -0,0 +1,49 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional + +from .._models import BaseModel + +__all__ = ["ProvidersCatalogEntry", "Settings"] + + +class Settings(BaseModel): + """Describes a single configuration field in the provider catalog.""" + + required: bool + """Whether this field is required when configuring the provider.""" + + type: str + """The field's data type (e.g. "string", "boolean", "enum").""" + + values: Optional[List[str]] = None + """Allowed values when `type` is "enum".""" + + +class ProvidersCatalogEntry(BaseModel): + """A provider type from the catalog. + + Contains the key, display name, description, and a `settings` object describing configuration schema fields. + """ + + channel: str + """Courier taxonomy channel (e.g. + + email, push, sms, direct_message, inbox, webhook). + """ + + description: str + """Short description of the provider.""" + + name: str + """Human-readable display name.""" + + provider: str + """The provider key (e.g. "sendgrid", "twilio").""" + + settings: Dict[str, Settings] + """Map of setting field names (snake_case) to their schema descriptors. + + Each descriptor has `type` and `required`. Empty when the provider has no + configurable schema. + """ diff --git a/src/courier/types/publish_preferences_response.py b/src/courier/types/publish_preferences_response.py new file mode 100644 index 00000000..c179b5ca --- /dev/null +++ b/src/courier/types/publish_preferences_response.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["PublishPreferencesResponse"] + + +class PublishPreferencesResponse(BaseModel): + """Result of publishing the workspace's preferences page.""" + + page_id: str + """Id of the published page snapshot.""" + + published_at: str + """ISO-8601 timestamp of the publish.""" + + published_version: float + """Monotonic published version (epoch milliseconds).""" + + preview_url: Optional[str] = None + """Draft-mode hosted preferences page URL for previewing.""" + + published_by: Optional[str] = None + """Id of the publisher.""" diff --git a/src/courier/types/put_subscriptions_recipient_param.py b/src/courier/types/put_subscriptions_recipient_param.py new file mode 100644 index 00000000..29a25425 --- /dev/null +++ b/src/courier/types/put_subscriptions_recipient_param.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .shared_params.recipient_preferences import RecipientPreferences + +__all__ = ["PutSubscriptionsRecipientParam"] + + +class PutSubscriptionsRecipientParam(TypedDict, total=False): + recipient_id: Required[Annotated[str, PropertyInfo(alias="recipientId")]] + + preferences: Optional[RecipientPreferences] diff --git a/src/courier/types/put_tenant_template_response.py b/src/courier/types/put_tenant_template_response.py new file mode 100644 index 00000000..3f5dd524 --- /dev/null +++ b/src/courier/types/put_tenant_template_response.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["PutTenantTemplateResponse"] + + +class PutTenantTemplateResponse(BaseModel): + """Response from creating or updating a tenant notification template""" + + id: str + """The template ID""" + + version: str + """The version of the saved template""" + + published_at: Optional[str] = None + """The timestamp when the template was published. + + Only present if the template was published as part of this request. + """ diff --git a/src/courier/types/routing_strategy_create_params.py b/src/courier/types/routing_strategy_create_params.py new file mode 100644 index 00000000..72a5e0df --- /dev/null +++ b/src/courier/types/routing_strategy_create_params.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._types import SequenceNotStr +from .._utils import PropertyInfo +from .shared_params.message_channels import MessageChannels +from .shared_params.message_providers import MessageProviders + +__all__ = ["RoutingStrategyCreateParams"] + + +class RoutingStrategyCreateParams(TypedDict, total=False): + name: Required[str] + """Human-readable name for the routing strategy.""" + + routing: Required["MessageRouting"] + """Routing tree defining channel selection method and order.""" + + channels: Optional[MessageChannels] + """Per-channel delivery configuration. Defaults to empty if omitted.""" + + description: Optional[str] + """Optional description of the routing strategy.""" + + providers: Optional[MessageProviders] + """Per-provider delivery configuration. Defaults to empty if omitted.""" + + tags: Optional[SequenceNotStr[str]] + """Optional tags for categorization.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +from .shared_params.message_routing import MessageRouting diff --git a/src/courier/types/routing_strategy_get_response.py b/src/courier/types/routing_strategy_get_response.py new file mode 100644 index 00000000..84fad4bf --- /dev/null +++ b/src/courier/types/routing_strategy_get_response.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional + +from .._models import BaseModel +from .shared.message_channels import MessageChannels +from .shared.message_providers import MessageProviders + +__all__ = ["RoutingStrategyGetResponse"] + + +class RoutingStrategyGetResponse(BaseModel): + """Full routing strategy entity returned by GET.""" + + id: str + """The routing strategy ID (rs\\__ prefix).""" + + channels: MessageChannels + """Per-channel delivery configuration. May be empty.""" + + created: int + """Epoch milliseconds when the strategy was created.""" + + creator: str + """User ID of the creator.""" + + name: str + """Human-readable name.""" + + providers: MessageProviders + """Per-provider delivery configuration. May be empty.""" + + routing: "MessageRouting" + """Routing tree defining channel selection method and order.""" + + description: Optional[str] = None + """Description of the routing strategy.""" + + tags: Optional[List[str]] = None + """Tags for categorization.""" + + updated: Optional[int] = None + """Epoch milliseconds of last update.""" + + updater: Optional[str] = None + """User ID of the last updater.""" + + +from .shared.message_routing import MessageRouting diff --git a/src/courier/types/routing_strategy_list_notifications_params.py b/src/courier/types/routing_strategy_list_notifications_params.py new file mode 100644 index 00000000..7e125462 --- /dev/null +++ b/src/courier/types/routing_strategy_list_notifications_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["RoutingStrategyListNotificationsParams"] + + +class RoutingStrategyListNotificationsParams(TypedDict, total=False): + cursor: Optional[str] + """Opaque pagination cursor from a previous response. Omit for the first page.""" + + limit: int + """Maximum number of results per page. Default 20, max 100.""" diff --git a/src/courier/types/routing_strategy_list_params.py b/src/courier/types/routing_strategy_list_params.py new file mode 100644 index 00000000..886ab22b --- /dev/null +++ b/src/courier/types/routing_strategy_list_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["RoutingStrategyListParams"] + + +class RoutingStrategyListParams(TypedDict, total=False): + cursor: Optional[str] + """Opaque pagination cursor from a previous response. Omit for the first page.""" + + limit: int + """Maximum number of results per page. Default 20, max 100.""" diff --git a/src/courier/types/routing_strategy_list_response.py b/src/courier/types/routing_strategy_list_response.py new file mode 100644 index 00000000..0f66d472 --- /dev/null +++ b/src/courier/types/routing_strategy_list_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .shared.paging import Paging +from .routing_strategy_summary import RoutingStrategySummary + +__all__ = ["RoutingStrategyListResponse"] + + +class RoutingStrategyListResponse(BaseModel): + """Paginated list of routing strategy summaries.""" + + paging: Paging + + results: List[RoutingStrategySummary] diff --git a/src/courier/types/routing_strategy_replace_params.py b/src/courier/types/routing_strategy_replace_params.py new file mode 100644 index 00000000..fa9258fd --- /dev/null +++ b/src/courier/types/routing_strategy_replace_params.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from .._types import SequenceNotStr +from .shared_params.message_channels import MessageChannels +from .shared_params.message_providers import MessageProviders + +__all__ = ["RoutingStrategyReplaceParams"] + + +class RoutingStrategyReplaceParams(TypedDict, total=False): + name: Required[str] + """Human-readable name for the routing strategy.""" + + routing: Required["MessageRouting"] + """Routing tree defining channel selection method and order.""" + + channels: Optional[MessageChannels] + """Per-channel delivery configuration. Omit to clear.""" + + description: Optional[str] + """Optional description. Omit or null to clear.""" + + providers: Optional[MessageProviders] + """Per-provider delivery configuration. Omit to clear.""" + + tags: Optional[SequenceNotStr[str]] + """Optional tags. Omit or null to clear.""" + + +from .shared_params.message_routing import MessageRouting diff --git a/src/courier/types/routing_strategy_summary.py b/src/courier/types/routing_strategy_summary.py new file mode 100644 index 00000000..842ebb92 --- /dev/null +++ b/src/courier/types/routing_strategy_summary.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["RoutingStrategySummary"] + + +class RoutingStrategySummary(BaseModel): + """Routing strategy metadata returned in list responses. + + Does not include routing/channels/providers content. + """ + + id: str + """The routing strategy ID (rs\\__ prefix).""" + + created: int + """Epoch milliseconds when the strategy was created.""" + + creator: str + """User ID of the creator.""" + + name: str + """Human-readable name.""" + + description: Optional[str] = None + """Description of the routing strategy.""" + + tags: Optional[List[str]] = None + """Tags for categorization.""" + + updated: Optional[int] = None + """Epoch milliseconds of last update.""" + + updater: Optional[str] = None + """User ID of the last updater.""" diff --git a/src/courier/types/send_message_params.py b/src/courier/types/send_message_params.py new file mode 100644 index 00000000..f365ac64 --- /dev/null +++ b/src/courier/types/send_message_params.py @@ -0,0 +1,183 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from .._types import SequenceNotStr +from .._utils import PropertyInfo +from .shared_params.utm import Utm +from .shared_params.list_recipient import ListRecipient +from .shared_params.user_recipient import UserRecipient +from .shared_params.message_context import MessageContext +from .shared_params.slack_recipient import SlackRecipient +from .shared_params.message_channels import MessageChannels +from .shared_params.elemental_content import ElementalContent +from .shared_params.message_providers import MessageProviders +from .shared_params.webhook_recipient import WebhookRecipient +from .shared_params.audience_recipient import AudienceRecipient +from .shared_params.ms_teams_recipient import MsTeamsRecipient +from .shared_params.pagerduty_recipient import PagerdutyRecipient +from .shared_params.list_pattern_recipient import ListPatternRecipient +from .shared_params.elemental_content_sugar import ElementalContentSugar + +__all__ = [ + "SendMessageParams", + "Message", + "MessageContent", + "MessageDelay", + "MessageExpiry", + "MessageMetadata", + "MessagePreferences", + "MessageRouting", + "MessageTimeout", + "MessageTo", + "MessageToUnionMember8", +] + + +class SendMessageParams(TypedDict, total=False): + message: Required[Message] + """The message property has the following primary top-level properties. + + They define the destination and content of the message. + """ + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +MessageContent: TypeAlias = Union[ElementalContentSugar, ElementalContent] + + +class MessageDelay(TypedDict, total=False): + duration: Optional[int] + """The duration of the delay in milliseconds.""" + + timezone: Optional[str] + """IANA timezone identifier (e.g., "America/Los_Angeles", "UTC"). + + Used when resolving opening hours expressions. Takes precedence over user + profile timezone settings. + """ + + until: Optional[str] + """ISO 8601 timestamp or opening_hours-like format.""" + + +class MessageExpiry(TypedDict, total=False): + expires_in: Required[Union[str, int]] + """Duration in ms or ISO8601 duration (e.g. P1DT4H).""" + + expires_at: Optional[str] + """Epoch or ISO8601 timestamp with timezone.""" + + +class MessageMetadata(TypedDict, total=False): + event: Optional[str] + + tags: Optional[SequenceNotStr[str]] + + trace_id: Optional[str] + + utm: Optional[Utm] + + +class MessagePreferences(TypedDict, total=False): + subscription_topic_id: Required[str] + """The subscription topic to apply to the message.""" + + +class MessageRouting(TypedDict, total=False): + """Customize which channels/providers Courier may deliver the message through.""" + + channels: Required[SequenceNotStr["MessageRoutingChannel"]] + """A list of channels or providers (or nested routing rules).""" + + method: Required[Literal["all", "single"]] + + +class MessageTimeout(TypedDict, total=False): + channel: Optional[Dict[str, int]] + + criteria: Optional[Literal["no-escalation", "delivered", "viewed", "engaged"]] + + escalation: Optional[int] + + message: Optional[int] + + provider: Optional[Dict[str, int]] + + +MessageToUnionMember8: TypeAlias = Union[ + UserRecipient, + AudienceRecipient, + ListRecipient, + ListPatternRecipient, + SlackRecipient, + MsTeamsRecipient, + PagerdutyRecipient, + WebhookRecipient, +] + +MessageTo: TypeAlias = Union[ + UserRecipient, + AudienceRecipient, + ListRecipient, + ListPatternRecipient, + SlackRecipient, + MsTeamsRecipient, + PagerdutyRecipient, + WebhookRecipient, + Iterable[MessageToUnionMember8], +] + + +class Message(TypedDict, total=False): + """The message property has the following primary top-level properties. + + They define the destination and content of the message. + """ + + brand_id: Optional[str] + + channels: Optional[MessageChannels] + """Define run-time configuration for channels. + + Valid ChannelId's: email, sms, push, inbox, direct_message, banner, webhook. + """ + + content: MessageContent + """ + Describes content that will work for email, inbox, push, chat, or any channel + id. + """ + + context: Optional[MessageContext] + + data: Optional[Dict[str, object]] + + delay: Optional[MessageDelay] + + expiry: Optional[MessageExpiry] + + metadata: Optional[MessageMetadata] + + preferences: Optional[MessagePreferences] + + providers: Optional[MessageProviders] + + routing: Optional[MessageRouting] + """Customize which channels/providers Courier may deliver the message through.""" + + template: Optional[str] + + timeout: Optional[MessageTimeout] + + to: Optional[MessageTo] + """The recipient or a list of recipients of the message""" + + +from .shared_params.message_routing_channel import MessageRoutingChannel diff --git a/src/courier/types/send_message_response.py b/src/courier/types/send_message_response.py new file mode 100644 index 00000000..64880255 --- /dev/null +++ b/src/courier/types/send_message_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["SendMessageResponse"] + + +class SendMessageResponse(BaseModel): + request_id: str = FieldInfo(alias="requestId") + """ + A successful call to `POST /send` returns a `202` status code along with a + `requestId` in the response body. For single-recipient requests, the `requestId` + is the derived message_id. For multiple recipients, Courier assigns a unique + message_id to each derived message. + """ diff --git a/src/courier/types/shared/__init__.py b/src/courier/types/shared/__init__.py new file mode 100644 index 00000000..94a89df2 --- /dev/null +++ b/src/courier/types/shared/__init__.py @@ -0,0 +1,79 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .utm import Utm as Utm +from .expo import Expo as Expo +from .rule import Rule as Rule +from .slack import Slack as Slack +from .token import Token as Token +from .paging import Paging as Paging +from .channel import Channel as Channel +from .discord import Discord as Discord +from .intercom import Intercom as Intercom +from .metadata import Metadata as Metadata +from .ms_teams import MsTeams as MsTeams +from .timeouts import Timeouts as Timeouts +from .alignment import Alignment as Alignment +from .pagerduty import Pagerduty as Pagerduty +from .preference import Preference as Preference +from .text_style import TextStyle as TextStyle +from .device_type import DeviceType as DeviceType +from .list_filter import ListFilter as ListFilter +from .user_profile import UserProfile as UserProfile +from .filter_config import FilterConfig as FilterConfig +from .elemental_node import ElementalNode as ElementalNode +from .list_recipient import ListRecipient as ListRecipient +from .user_recipient import UserRecipient as UserRecipient +from .webhook_method import WebhookMethod as WebhookMethod +from .airship_profile import AirshipProfile as AirshipProfile +from .audience_filter import AudienceFilter as AudienceFilter +from .message_context import MessageContext as MessageContext +from .message_routing import MessageRouting as MessageRouting +from .multiple_tokens import MultipleTokens as MultipleTokens +from .send_to_channel import SendToChannel as SendToChannel +from .slack_recipient import SlackRecipient as SlackRecipient +from .webhook_profile import WebhookProfile as WebhookProfile +from .channel_metadata import ChannelMetadata as ChannelMetadata +from .message_channels import MessageChannels as MessageChannels +from .elemental_content import ElementalContent as ElementalContent +from .message_providers import MessageProviders as MessageProviders +from .preference_status import PreferenceStatus as PreferenceStatus +from .webhook_auth_mode import WebhookAuthMode as WebhookAuthMode +from .webhook_recipient import WebhookRecipient as WebhookRecipient +from .audience_recipient import AudienceRecipient as AudienceRecipient +from .channel_preference import ChannelPreference as ChannelPreference +from .intercom_recipient import IntercomRecipient as IntercomRecipient +from .ms_teams_recipient import MsTeamsRecipient as MsTeamsRecipient +from .elemental_base_node import ElementalBaseNode as ElementalBaseNode +from .pagerduty_recipient import PagerdutyRecipient as PagerdutyRecipient +from .send_direct_message import SendDirectMessage as SendDirectMessage +from .send_to_slack_email import SendToSlackEmail as SendToSlackEmail +from .webhook_profile_type import WebhookProfileType as WebhookProfileType +from .recipient_preferences import RecipientPreferences as RecipientPreferences +from .send_to_slack_channel import SendToSlackChannel as SendToSlackChannel +from .send_to_slack_user_id import SendToSlackUserID as SendToSlackUserID +from .slack_base_properties import SlackBaseProperties as SlackBaseProperties +from .audience_filter_config import AudienceFilterConfig as AudienceFilterConfig +from .channel_classification import ChannelClassification as ChannelClassification +from .elemental_channel_node import ElementalChannelNode as ElementalChannelNode +from .list_pattern_recipient import ListPatternRecipient as ListPatternRecipient +from .message_providers_type import MessageProvidersType as MessageProvidersType +from .send_to_ms_teams_email import SendToMsTeamsEmail as SendToMsTeamsEmail +from .webhook_authentication import WebhookAuthentication as WebhookAuthentication +from .elemental_content_sugar import ElementalContentSugar as ElementalContentSugar +from .message_routing_channel import MessageRoutingChannel as MessageRoutingChannel +from .airship_profile_audience import AirshipProfileAudience as AirshipProfileAudience +from .ms_teams_base_properties import MsTeamsBaseProperties as MsTeamsBaseProperties +from .send_to_ms_teams_user_id import SendToMsTeamsUserID as SendToMsTeamsUserID +from .send_to_ms_teams_channel_id import SendToMsTeamsChannelID as SendToMsTeamsChannelID +from .user_profile_firebase_token import UserProfileFirebaseToken as UserProfileFirebaseToken +from .elemental_html_node_with_type import ElementalHTMLNodeWithType as ElementalHTMLNodeWithType +from .elemental_meta_node_with_type import ElementalMetaNodeWithType as ElementalMetaNodeWithType +from .elemental_text_node_with_type import ElementalTextNodeWithType as ElementalTextNodeWithType +from .send_to_ms_teams_channel_name import SendToMsTeamsChannelName as SendToMsTeamsChannelName +from .elemental_image_node_with_type import ElementalImageNodeWithType as ElementalImageNodeWithType +from .elemental_quote_node_with_type import ElementalQuoteNodeWithType as ElementalQuoteNodeWithType +from .elemental_action_node_with_type import ElementalActionNodeWithType as ElementalActionNodeWithType +from .notification_preference_details import NotificationPreferenceDetails as NotificationPreferenceDetails +from .elemental_channel_node_with_type import ElementalChannelNodeWithType as ElementalChannelNodeWithType +from .elemental_divider_node_with_type import ElementalDividerNodeWithType as ElementalDividerNodeWithType +from .send_to_ms_teams_conversation_id import SendToMsTeamsConversationID as SendToMsTeamsConversationID diff --git a/src/courier/types/shared/airship_profile.py b/src/courier/types/shared/airship_profile.py new file mode 100644 index 00000000..9b8f757c --- /dev/null +++ b/src/courier/types/shared/airship_profile.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from .device_type import DeviceType +from .airship_profile_audience import AirshipProfileAudience + +__all__ = ["AirshipProfile"] + + +class AirshipProfile(BaseModel): + audience: AirshipProfileAudience + + device_types: List[DeviceType] diff --git a/src/courier/types/shared/airship_profile_audience.py b/src/courier/types/shared/airship_profile_audience.py new file mode 100644 index 00000000..b00cb2da --- /dev/null +++ b/src/courier/types/shared/airship_profile_audience.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["AirshipProfileAudience"] + + +class AirshipProfileAudience(BaseModel): + named_user: str diff --git a/src/courier/types/shared/alignment.py b/src/courier/types/shared/alignment.py new file mode 100644 index 00000000..f6a0073d --- /dev/null +++ b/src/courier/types/shared/alignment.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["Alignment"] + +Alignment: TypeAlias = Literal["center", "left", "right", "full"] diff --git a/src/courier/types/shared/audience_filter.py b/src/courier/types/shared/audience_filter.py new file mode 100644 index 00000000..b1092a9f --- /dev/null +++ b/src/courier/types/shared/audience_filter.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["AudienceFilter"] + + +class AudienceFilter(BaseModel): + operator: Literal["MEMBER_OF"] + """Send to users only if they are member of the account""" + + path: Literal["account_id"] + + value: str diff --git a/src/courier/types/shared/audience_filter_config.py b/src/courier/types/shared/audience_filter_config.py new file mode 100644 index 00000000..74516d9c --- /dev/null +++ b/src/courier/types/shared/audience_filter_config.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["AudienceFilterConfig"] + + +class AudienceFilterConfig(BaseModel): + """ + Filter configuration for audience membership containing an array of filter rules + """ + + filters: List["FilterConfig"] + """Array of filter rules (single conditions or nested groups)""" + + operator: Optional[Literal["AND", "OR"]] = None + """The logical operator (AND/OR) combining the rules in `filters`. + + Required when `filters` contains more than one rule. If omitted, the top-level + `operator` field on the request is used instead. + """ + + +from .filter_config import FilterConfig diff --git a/src/courier/types/shared/audience_recipient.py b/src/courier/types/shared/audience_recipient.py new file mode 100644 index 00000000..f1d772dc --- /dev/null +++ b/src/courier/types/shared/audience_recipient.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional + +from ..._models import BaseModel +from .audience_filter import AudienceFilter + +__all__ = ["AudienceRecipient"] + + +class AudienceRecipient(BaseModel): + """Send to all users in an audience""" + + audience_id: str + """A unique identifier associated with an Audience. + + A message will be sent to each user in the audience. + """ + + data: Optional[Dict[str, object]] = None + + filters: Optional[List[AudienceFilter]] = None diff --git a/src/courier/types/shared/channel.py b/src/courier/types/shared/channel.py new file mode 100644 index 00000000..ecbd384a --- /dev/null +++ b/src/courier/types/shared/channel.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .timeouts import Timeouts +from ..._models import BaseModel +from .channel_metadata import ChannelMetadata + +__all__ = ["Channel"] + + +class Channel(BaseModel): + brand_id: Optional[str] = None + """Brand id used for rendering.""" + + if_: Optional[str] = FieldInfo(alias="if", default=None) + """JS conditional with access to data/profile.""" + + metadata: Optional[ChannelMetadata] = None + + override: Optional[Dict[str, object]] = None + """Channel specific overrides.""" + + providers: Optional[List[str]] = None + """Providers enabled for this channel.""" + + routing_method: Optional[Literal["all", "single"]] = None + """Defaults to `single`.""" + + timeouts: Optional[Timeouts] = None diff --git a/src/courier/types/shared/channel_classification.py b/src/courier/types/shared/channel_classification.py new file mode 100644 index 00000000..f158e84f --- /dev/null +++ b/src/courier/types/shared/channel_classification.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ChannelClassification"] + +ChannelClassification: TypeAlias = Literal["direct_message", "email", "push", "sms", "webhook", "inbox"] diff --git a/src/courier/types/shared/channel_metadata.py b/src/courier/types/shared/channel_metadata.py new file mode 100644 index 00000000..c4973e94 --- /dev/null +++ b/src/courier/types/shared/channel_metadata.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .utm import Utm +from ..._models import BaseModel + +__all__ = ["ChannelMetadata"] + + +class ChannelMetadata(BaseModel): + utm: Optional[Utm] = None diff --git a/src/courier/types/shared/channel_preference.py b/src/courier/types/shared/channel_preference.py new file mode 100644 index 00000000..c09394a1 --- /dev/null +++ b/src/courier/types/shared/channel_preference.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .channel_classification import ChannelClassification + +__all__ = ["ChannelPreference"] + + +class ChannelPreference(BaseModel): + channel: ChannelClassification diff --git a/src/courier/types/shared/device_type.py b/src/courier/types/shared/device_type.py new file mode 100644 index 00000000..add61857 --- /dev/null +++ b/src/courier/types/shared/device_type.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import TypeAlias + +__all__ = ["DeviceType"] + +DeviceType: TypeAlias = str diff --git a/src/courier/types/shared/discord.py b/src/courier/types/shared/discord.py new file mode 100644 index 00000000..f809db8f --- /dev/null +++ b/src/courier/types/shared/discord.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .send_to_channel import SendToChannel +from .send_direct_message import SendDirectMessage + +__all__ = ["Discord"] + +Discord: TypeAlias = Union[SendToChannel, SendDirectMessage] diff --git a/src/courier/types/shared/elemental_action_node_with_type.py b/src/courier/types/shared/elemental_action_node_with_type.py new file mode 100644 index 00000000..f0420acb --- /dev/null +++ b/src/courier/types/shared/elemental_action_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalActionNodeWithType"] + + +class ElementalActionNodeWithType(ElementalBaseNode): + type: Optional[Literal["action"]] = None diff --git a/src/courier/types/shared/elemental_base_node.py b/src/courier/types/shared/elemental_base_node.py new file mode 100644 index 00000000..adb41017 --- /dev/null +++ b/src/courier/types/shared/elemental_base_node.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from pydantic import Field as FieldInfo + +from ..._models import BaseModel + +__all__ = ["ElementalBaseNode"] + + +class ElementalBaseNode(BaseModel): + channels: Optional[List[str]] = None + + if_: Optional[str] = FieldInfo(alias="if", default=None) + + loop: Optional[str] = None + + ref: Optional[str] = None diff --git a/src/courier/types/shared/elemental_channel_node.py b/src/courier/types/shared/elemental_channel_node.py new file mode 100644 index 00000000..e8200886 --- /dev/null +++ b/src/courier/types/shared/elemental_channel_node.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalChannelNode"] + + +class ElementalChannelNode(ElementalBaseNode): + """ + The channel element allows a notification to be customized based on which channel it is sent through. + For example, you may want to display a detailed message when the notification is sent through email, + and a more concise message in a push notification. Channel elements are only valid as top-level + elements; you cannot nest channel elements. If there is a channel element specified at the top-level + of the document, all sibling elements must be channel elements. + Note: As an alternative, most elements support a `channel` property. Which allows you to selectively + display an individual element on a per channel basis. See the + [control flow docs](https://www.courier.com/docs/platform/content/elemental/control-flow/) for more details. + """ + + channel: Optional[str] = None + """The channel the contents of this element should be applied to. + + Can be `email`, `push`, `direct_message`, `sms` or a provider such as slack + """ + + font_size: Optional[str] = None + """Email only. + + Document-level base font size (CSS px, e.g. `16px`) for body content — text, + quote, list and action button labels. Heading styles (`h1`/`h2`/`h3`) and + `subtext` keep their preset sizes. + """ + + line_height: Optional[str] = None + """Email only. + + Document-level line height (CSS px or unitless multiplier, e.g. `24px` or `1.5`) + applied to all body content unless overridden per block. + """ + + padding: Optional[str] = None + """Email only. + + Document-level body padding applied once around the email body, as a CSS px + shorthand (1–4 values), e.g. `48px 64px`. + """ + + raw: Optional[Dict[str, object]] = None + """Raw data to apply to the channel. + + If `elements` has not been specified, `raw` is required. + """ diff --git a/src/courier/types/shared/elemental_channel_node_with_type.py b/src/courier/types/shared/elemental_channel_node_with_type.py new file mode 100644 index 00000000..91dd5c03 --- /dev/null +++ b/src/courier/types/shared/elemental_channel_node_with_type.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_channel_node import ElementalChannelNode + +__all__ = ["ElementalChannelNodeWithType"] + + +class ElementalChannelNodeWithType(ElementalChannelNode): + """ + The channel element allows a notification to be customized based on which channel it is sent through. + For example, you may want to display a detailed message when the notification is sent through email, + and a more concise message in a push notification. Channel elements are only valid as top-level + elements; you cannot nest channel elements. If there is a channel element specified at the top-level + of the document, all sibling elements must be channel elements. + Note: As an alternative, most elements support a `channel` property. Which allows you to selectively + display an individual element on a per channel basis. See the + [control flow docs](https://www.courier.com/docs/platform/content/elemental/control-flow/) for more details. + """ + + type: Optional[Literal["channel"]] = None diff --git a/src/courier/types/shared/elemental_content.py b/src/courier/types/shared/elemental_content.py new file mode 100644 index 00000000..24d06365 --- /dev/null +++ b/src/courier/types/shared/elemental_content.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from .elemental_node import ElementalNode + +__all__ = ["ElementalContent"] + + +class ElementalContent(BaseModel): + elements: List[ElementalNode] + + version: str + """For example, "2022-01-01" """ diff --git a/src/courier/types/shared/elemental_content_sugar.py b/src/courier/types/shared/elemental_content_sugar.py new file mode 100644 index 00000000..52c09e4e --- /dev/null +++ b/src/courier/types/shared/elemental_content_sugar.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["ElementalContentSugar"] + + +class ElementalContentSugar(BaseModel): + """Syntactic sugar to provide a fast shorthand for Courier Elemental Blocks.""" + + body: str + """The text content displayed in the notification.""" + + title: str + """Title/subject displayed by supported channels.""" diff --git a/src/courier/types/shared/elemental_divider_node_with_type.py b/src/courier/types/shared/elemental_divider_node_with_type.py new file mode 100644 index 00000000..6b5725ed --- /dev/null +++ b/src/courier/types/shared/elemental_divider_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalDividerNodeWithType"] + + +class ElementalDividerNodeWithType(ElementalBaseNode): + type: Optional[Literal["divider"]] = None diff --git a/src/courier/types/shared/elemental_html_node_with_type.py b/src/courier/types/shared/elemental_html_node_with_type.py new file mode 100644 index 00000000..3df93b25 --- /dev/null +++ b/src/courier/types/shared/elemental_html_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalHTMLNodeWithType"] + + +class ElementalHTMLNodeWithType(ElementalBaseNode): + type: Optional[Literal["html"]] = None diff --git a/src/courier/types/shared/elemental_image_node_with_type.py b/src/courier/types/shared/elemental_image_node_with_type.py new file mode 100644 index 00000000..48daaa3d --- /dev/null +++ b/src/courier/types/shared/elemental_image_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalImageNodeWithType"] + + +class ElementalImageNodeWithType(ElementalBaseNode): + type: Optional[Literal["image"]] = None diff --git a/src/courier/types/shared/elemental_meta_node_with_type.py b/src/courier/types/shared/elemental_meta_node_with_type.py new file mode 100644 index 00000000..0f8b5c0b --- /dev/null +++ b/src/courier/types/shared/elemental_meta_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalMetaNodeWithType"] + + +class ElementalMetaNodeWithType(ElementalBaseNode): + type: Optional[Literal["meta"]] = None diff --git a/src/courier/types/shared/elemental_node.py b/src/courier/types/shared/elemental_node.py new file mode 100644 index 00000000..c057d31a --- /dev/null +++ b/src/courier/types/shared/elemental_node.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .elemental_html_node_with_type import ElementalHTMLNodeWithType +from .elemental_meta_node_with_type import ElementalMetaNodeWithType +from .elemental_text_node_with_type import ElementalTextNodeWithType +from .elemental_image_node_with_type import ElementalImageNodeWithType +from .elemental_quote_node_with_type import ElementalQuoteNodeWithType +from .elemental_action_node_with_type import ElementalActionNodeWithType +from .elemental_channel_node_with_type import ElementalChannelNodeWithType +from .elemental_divider_node_with_type import ElementalDividerNodeWithType + +__all__ = ["ElementalNode"] + +ElementalNode: TypeAlias = Union[ + ElementalTextNodeWithType, + ElementalMetaNodeWithType, + ElementalChannelNodeWithType, + ElementalImageNodeWithType, + ElementalActionNodeWithType, + ElementalDividerNodeWithType, + ElementalQuoteNodeWithType, + ElementalHTMLNodeWithType, +] diff --git a/src/courier/types/shared/elemental_quote_node_with_type.py b/src/courier/types/shared/elemental_quote_node_with_type.py new file mode 100644 index 00000000..9323d619 --- /dev/null +++ b/src/courier/types/shared/elemental_quote_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalQuoteNodeWithType"] + + +class ElementalQuoteNodeWithType(ElementalBaseNode): + type: Optional[Literal["quote"]] = None diff --git a/src/courier/types/shared/elemental_text_node_with_type.py b/src/courier/types/shared/elemental_text_node_with_type.py new file mode 100644 index 00000000..5e5fd4e8 --- /dev/null +++ b/src/courier/types/shared/elemental_text_node_with_type.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalTextNodeWithType"] + + +class ElementalTextNodeWithType(ElementalBaseNode): + type: Optional[Literal["text"]] = None diff --git a/src/courier/types/shared/expo.py b/src/courier/types/shared/expo.py new file mode 100644 index 00000000..f99b235e --- /dev/null +++ b/src/courier/types/shared/expo.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .token import Token +from .multiple_tokens import MultipleTokens + +__all__ = ["Expo"] + +Expo: TypeAlias = Union[Token, MultipleTokens] diff --git a/src/courier/types/shared/filter_config.py b/src/courier/types/shared/filter_config.py new file mode 100644 index 00000000..203485a7 --- /dev/null +++ b/src/courier/types/shared/filter_config.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional + +from ..._models import BaseModel + +__all__ = ["FilterConfig"] + + +class FilterConfig(BaseModel): + """ + A filter rule that can be either a single condition (with path/value) or a nested group (with filters array). Use comparison operators (EQ, GT, etc.) for single conditions, and logical operators (AND, OR) for nested groups. + """ + + operator: str + """The operator for this filter. + + Use comparison operators (EQ, GT, LT, GTE, LTE, NEQ, EXISTS, INCLUDES, + STARTS_WITH, ENDS_WITH, IS_BEFORE, IS_AFTER, OMIT) for single conditions, or + logical operators (AND, OR) for nested filter groups. + """ + + filters: Optional[List["FilterConfig"]] = None + """Nested filter rules to combine with AND/OR. + + Required for nested filter groups, not used for single filter conditions. + """ + + path: Optional[str] = None + """The attribute path from the user profile to filter on. + + Required for single filter conditions, not used for nested filter groups. + """ + + value: Optional[str] = None + """The value to compare against. + + Required for single filter conditions, not used for nested filter groups. + """ diff --git a/src/courier/types/shared/intercom.py b/src/courier/types/shared/intercom.py new file mode 100644 index 00000000..f28d1f6e --- /dev/null +++ b/src/courier/types/shared/intercom.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from pydantic import Field as FieldInfo + +from ..._models import BaseModel +from .intercom_recipient import IntercomRecipient + +__all__ = ["Intercom"] + + +class Intercom(BaseModel): + from_: str = FieldInfo(alias="from") + + to: IntercomRecipient diff --git a/src/courier/types/shared/intercom_recipient.py b/src/courier/types/shared/intercom_recipient.py new file mode 100644 index 00000000..d560f72c --- /dev/null +++ b/src/courier/types/shared/intercom_recipient.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["IntercomRecipient"] + + +class IntercomRecipient(BaseModel): + id: str diff --git a/src/courier/types/shared/list_filter.py b/src/courier/types/shared/list_filter.py new file mode 100644 index 00000000..07c5fc13 --- /dev/null +++ b/src/courier/types/shared/list_filter.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ListFilter"] + + +class ListFilter(BaseModel): + operator: Literal["MEMBER_OF"] + """Send to users only if they are member of the account""" + + path: Literal["account_id"] + + value: str diff --git a/src/courier/types/shared/list_pattern_recipient.py b/src/courier/types/shared/list_pattern_recipient.py new file mode 100644 index 00000000..67431305 --- /dev/null +++ b/src/courier/types/shared/list_pattern_recipient.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from ..._models import BaseModel + +__all__ = ["ListPatternRecipient"] + + +class ListPatternRecipient(BaseModel): + """Send to users in lists matching a pattern""" + + data: Optional[Dict[str, object]] = None + + list_pattern: Optional[str] = None diff --git a/src/courier/types/shared/list_recipient.py b/src/courier/types/shared/list_recipient.py new file mode 100644 index 00000000..19a4a325 --- /dev/null +++ b/src/courier/types/shared/list_recipient.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional + +from ..._models import BaseModel +from .list_filter import ListFilter + +__all__ = ["ListRecipient"] + + +class ListRecipient(BaseModel): + """Send to all users in a specific list""" + + data: Optional[Dict[str, object]] = None + + filters: Optional[List[ListFilter]] = None + + list_id: Optional[str] = None diff --git a/src/courier/types/shared/message_channels.py b/src/courier/types/shared/message_channels.py new file mode 100644 index 00000000..97494d41 --- /dev/null +++ b/src/courier/types/shared/message_channels.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import TypeAlias + +from .channel import Channel + +__all__ = ["MessageChannels"] + +MessageChannels: TypeAlias = Dict[str, Channel] diff --git a/src/courier/types/shared/message_context.py b/src/courier/types/shared/message_context.py new file mode 100644 index 00000000..db91b6c2 --- /dev/null +++ b/src/courier/types/shared/message_context.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["MessageContext"] + + +class MessageContext(BaseModel): + tenant_id: Optional[str] = None + """Tenant id used to load brand/default preferences/context.""" diff --git a/src/courier/types/shared/message_providers.py b/src/courier/types/shared/message_providers.py new file mode 100644 index 00000000..d152471f --- /dev/null +++ b/src/courier/types/shared/message_providers.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import TypeAlias + +from .message_providers_type import MessageProvidersType + +__all__ = ["MessageProviders"] + +MessageProviders: TypeAlias = Dict[str, MessageProvidersType] diff --git a/src/courier/types/shared/message_providers_type.py b/src/courier/types/shared/message_providers_type.py new file mode 100644 index 00000000..c48e2bb6 --- /dev/null +++ b/src/courier/types/shared/message_providers_type.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from pydantic import Field as FieldInfo + +from .metadata import Metadata +from ..._models import BaseModel + +__all__ = ["MessageProvidersType"] + + +class MessageProvidersType(BaseModel): + if_: Optional[str] = FieldInfo(alias="if", default=None) + """JS conditional with access to data/profile.""" + + metadata: Optional[Metadata] = None + + override: Optional[Dict[str, object]] = None + """Provider-specific overrides.""" + + timeouts: Optional[int] = None diff --git a/src/courier/types/shared/message_routing.py b/src/courier/types/shared/message_routing.py new file mode 100644 index 00000000..a5c2962a --- /dev/null +++ b/src/courier/types/shared/message_routing.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["MessageRouting"] + + +class MessageRouting(BaseModel): + channels: List["MessageRoutingChannel"] + + method: Literal["all", "single"] + + +from .message_routing_channel import MessageRoutingChannel diff --git a/src/courier/types/shared/message_routing_channel.py b/src/courier/types/shared/message_routing_channel.py new file mode 100644 index 00000000..0183c4a1 --- /dev/null +++ b/src/courier/types/shared/message_routing_channel.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Union +from typing_extensions import TypeAlias, TypeAliasType + +from ..._compat import PYDANTIC_V1 + +__all__ = ["MessageRoutingChannel"] + +if TYPE_CHECKING or not PYDANTIC_V1: + MessageRoutingChannel = TypeAliasType("MessageRoutingChannel", Union[str, "MessageRouting"]) +else: + MessageRoutingChannel: TypeAlias = Union[str, "MessageRouting"] + +from .message_routing import MessageRouting diff --git a/src/courier/types/shared/metadata.py b/src/courier/types/shared/metadata.py new file mode 100644 index 00000000..d0e7aa55 --- /dev/null +++ b/src/courier/types/shared/metadata.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .utm import Utm +from ..._models import BaseModel + +__all__ = ["Metadata"] + + +class Metadata(BaseModel): + utm: Optional[Utm] = None diff --git a/src/courier/types/shared/ms_teams.py b/src/courier/types/shared/ms_teams.py new file mode 100644 index 00000000..911bb9fb --- /dev/null +++ b/src/courier/types/shared/ms_teams.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .send_to_ms_teams_email import SendToMsTeamsEmail +from .send_to_ms_teams_user_id import SendToMsTeamsUserID +from .send_to_ms_teams_channel_id import SendToMsTeamsChannelID +from .send_to_ms_teams_channel_name import SendToMsTeamsChannelName +from .send_to_ms_teams_conversation_id import SendToMsTeamsConversationID + +__all__ = ["MsTeams"] + +MsTeams: TypeAlias = Union[ + SendToMsTeamsUserID, + SendToMsTeamsEmail, + SendToMsTeamsChannelID, + SendToMsTeamsConversationID, + SendToMsTeamsChannelName, +] diff --git a/src/courier/types/shared/ms_teams_base_properties.py b/src/courier/types/shared/ms_teams_base_properties.py new file mode 100644 index 00000000..1764a509 --- /dev/null +++ b/src/courier/types/shared/ms_teams_base_properties.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["MsTeamsBaseProperties"] + + +class MsTeamsBaseProperties(BaseModel): + service_url: str + + tenant_id: str diff --git a/src/courier/types/shared/ms_teams_recipient.py b/src/courier/types/shared/ms_teams_recipient.py new file mode 100644 index 00000000..5e725752 --- /dev/null +++ b/src/courier/types/shared/ms_teams_recipient.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .ms_teams import MsTeams +from ..._models import BaseModel + +__all__ = ["MsTeamsRecipient"] + + +class MsTeamsRecipient(BaseModel): + """Send via Microsoft Teams""" + + ms_teams: MsTeams diff --git a/src/courier/types/shared/multiple_tokens.py b/src/courier/types/shared/multiple_tokens.py new file mode 100644 index 00000000..1e47c805 --- /dev/null +++ b/src/courier/types/shared/multiple_tokens.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .token import Token +from ..._models import BaseModel + +__all__ = ["MultipleTokens"] + + +class MultipleTokens(BaseModel): + tokens: List[Token] diff --git a/src/courier/types/shared/notification_preference_details.py b/src/courier/types/shared/notification_preference_details.py new file mode 100644 index 00000000..4a6cc0a4 --- /dev/null +++ b/src/courier/types/shared/notification_preference_details.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .rule import Rule +from ..._models import BaseModel +from .preference_status import PreferenceStatus +from .channel_preference import ChannelPreference + +__all__ = ["NotificationPreferenceDetails"] + + +class NotificationPreferenceDetails(BaseModel): + status: PreferenceStatus + + channel_preferences: Optional[List[ChannelPreference]] = None + + rules: Optional[List[Rule]] = None diff --git a/src/courier/types/shared/pagerduty.py b/src/courier/types/shared/pagerduty.py new file mode 100644 index 00000000..e6e5eb40 --- /dev/null +++ b/src/courier/types/shared/pagerduty.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["Pagerduty"] + + +class Pagerduty(BaseModel): + event_action: Optional[str] = None + + routing_key: Optional[str] = None + + severity: Optional[str] = None + + source: Optional[str] = None diff --git a/src/courier/types/shared/pagerduty_recipient.py b/src/courier/types/shared/pagerduty_recipient.py new file mode 100644 index 00000000..c4ed95e8 --- /dev/null +++ b/src/courier/types/shared/pagerduty_recipient.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .pagerduty import Pagerduty + +__all__ = ["PagerdutyRecipient"] + + +class PagerdutyRecipient(BaseModel): + """Send via PagerDuty""" + + pagerduty: Pagerduty diff --git a/src/courier/types/shared/paging.py b/src/courier/types/shared/paging.py new file mode 100644 index 00000000..6fafdd28 --- /dev/null +++ b/src/courier/types/shared/paging.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["Paging"] + + +class Paging(BaseModel): + more: bool + + cursor: Optional[str] = None diff --git a/src/courier/types/shared/preference.py b/src/courier/types/shared/preference.py new file mode 100644 index 00000000..7e79fe7e --- /dev/null +++ b/src/courier/types/shared/preference.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .rule import Rule +from ..._models import BaseModel +from .preference_status import PreferenceStatus +from .channel_preference import ChannelPreference + +__all__ = ["Preference"] + + +class Preference(BaseModel): + status: PreferenceStatus + + channel_preferences: Optional[List[ChannelPreference]] = None + + rules: Optional[List[Rule]] = None + + source: Optional[Literal["subscription", "list", "recipient"]] = None diff --git a/src/courier/types/shared/preference_status.py b/src/courier/types/shared/preference_status.py new file mode 100644 index 00000000..4bde1211 --- /dev/null +++ b/src/courier/types/shared/preference_status.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["PreferenceStatus"] + +PreferenceStatus: TypeAlias = Literal["OPTED_IN", "OPTED_OUT", "REQUIRED"] diff --git a/src/courier/types/shared/recipient_preferences.py b/src/courier/types/shared/recipient_preferences.py new file mode 100644 index 00000000..38a746e0 --- /dev/null +++ b/src/courier/types/shared/recipient_preferences.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from ..._models import BaseModel +from .notification_preference_details import NotificationPreferenceDetails + +__all__ = ["RecipientPreferences"] + + +class RecipientPreferences(BaseModel): + categories: Optional[Dict[str, NotificationPreferenceDetails]] = None + + notifications: Optional[Dict[str, NotificationPreferenceDetails]] = None diff --git a/src/courier/types/shared/rule.py b/src/courier/types/shared/rule.py new file mode 100644 index 00000000..d9345de7 --- /dev/null +++ b/src/courier/types/shared/rule.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["Rule"] + + +class Rule(BaseModel): + until: str + + start: Optional[str] = None diff --git a/src/courier/types/shared/send_direct_message.py b/src/courier/types/shared/send_direct_message.py new file mode 100644 index 00000000..3254e242 --- /dev/null +++ b/src/courier/types/shared/send_direct_message.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendDirectMessage"] + + +class SendDirectMessage(BaseModel): + user_id: str diff --git a/src/courier/types/shared/send_to_channel.py b/src/courier/types/shared/send_to_channel.py new file mode 100644 index 00000000..389b448a --- /dev/null +++ b/src/courier/types/shared/send_to_channel.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToChannel"] + + +class SendToChannel(BaseModel): + channel_id: str diff --git a/src/courier/types/shared/send_to_ms_teams_channel_id.py b/src/courier/types/shared/send_to_ms_teams_channel_id.py new file mode 100644 index 00000000..f51aeba1 --- /dev/null +++ b/src/courier/types/shared/send_to_ms_teams_channel_id.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToMsTeamsChannelID"] + + +class SendToMsTeamsChannelID(BaseModel): + channel_id: str + + service_url: str + + tenant_id: str diff --git a/src/courier/types/shared/send_to_ms_teams_channel_name.py b/src/courier/types/shared/send_to_ms_teams_channel_name.py new file mode 100644 index 00000000..bfc18062 --- /dev/null +++ b/src/courier/types/shared/send_to_ms_teams_channel_name.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToMsTeamsChannelName"] + + +class SendToMsTeamsChannelName(BaseModel): + channel_name: str + + service_url: str + + team_id: str + + tenant_id: str diff --git a/src/courier/types/shared/send_to_ms_teams_conversation_id.py b/src/courier/types/shared/send_to_ms_teams_conversation_id.py new file mode 100644 index 00000000..cbdf8f8d --- /dev/null +++ b/src/courier/types/shared/send_to_ms_teams_conversation_id.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToMsTeamsConversationID"] + + +class SendToMsTeamsConversationID(BaseModel): + conversation_id: str + + service_url: str + + tenant_id: str diff --git a/src/courier/types/shared/send_to_ms_teams_email.py b/src/courier/types/shared/send_to_ms_teams_email.py new file mode 100644 index 00000000..bd05c245 --- /dev/null +++ b/src/courier/types/shared/send_to_ms_teams_email.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToMsTeamsEmail"] + + +class SendToMsTeamsEmail(BaseModel): + email: str + + service_url: str + + tenant_id: str diff --git a/src/courier/types/shared/send_to_ms_teams_user_id.py b/src/courier/types/shared/send_to_ms_teams_user_id.py new file mode 100644 index 00000000..23787d6e --- /dev/null +++ b/src/courier/types/shared/send_to_ms_teams_user_id.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToMsTeamsUserID"] + + +class SendToMsTeamsUserID(BaseModel): + service_url: str + + tenant_id: str + + user_id: str diff --git a/src/courier/types/shared/send_to_slack_channel.py b/src/courier/types/shared/send_to_slack_channel.py new file mode 100644 index 00000000..d44c9ac6 --- /dev/null +++ b/src/courier/types/shared/send_to_slack_channel.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToSlackChannel"] + + +class SendToSlackChannel(BaseModel): + access_token: str + + channel: str diff --git a/src/courier/types/shared/send_to_slack_email.py b/src/courier/types/shared/send_to_slack_email.py new file mode 100644 index 00000000..83765a9d --- /dev/null +++ b/src/courier/types/shared/send_to_slack_email.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToSlackEmail"] + + +class SendToSlackEmail(BaseModel): + access_token: str + + email: str diff --git a/src/courier/types/shared/send_to_slack_user_id.py b/src/courier/types/shared/send_to_slack_user_id.py new file mode 100644 index 00000000..0227aa81 --- /dev/null +++ b/src/courier/types/shared/send_to_slack_user_id.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SendToSlackUserID"] + + +class SendToSlackUserID(BaseModel): + access_token: str + + user_id: str diff --git a/src/courier/types/shared/slack.py b/src/courier/types/shared/slack.py new file mode 100644 index 00000000..ba28a767 --- /dev/null +++ b/src/courier/types/shared/slack.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .send_to_slack_email import SendToSlackEmail +from .send_to_slack_channel import SendToSlackChannel +from .send_to_slack_user_id import SendToSlackUserID + +__all__ = ["Slack"] + +Slack: TypeAlias = Union[SendToSlackChannel, SendToSlackEmail, SendToSlackUserID] diff --git a/src/courier/types/shared/slack_base_properties.py b/src/courier/types/shared/slack_base_properties.py new file mode 100644 index 00000000..bf878837 --- /dev/null +++ b/src/courier/types/shared/slack_base_properties.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["SlackBaseProperties"] + + +class SlackBaseProperties(BaseModel): + access_token: str diff --git a/src/courier/types/shared/slack_recipient.py b/src/courier/types/shared/slack_recipient.py new file mode 100644 index 00000000..e3f2f68f --- /dev/null +++ b/src/courier/types/shared/slack_recipient.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .slack import Slack +from ..._models import BaseModel + +__all__ = ["SlackRecipient"] + + +class SlackRecipient(BaseModel): + """Send via Slack (channel, email, or user_id)""" + + slack: Slack diff --git a/src/courier/types/shared/text_style.py b/src/courier/types/shared/text_style.py new file mode 100644 index 00000000..a2840715 --- /dev/null +++ b/src/courier/types/shared/text_style.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["TextStyle"] + +TextStyle: TypeAlias = Literal["text", "h1", "h2", "subtext"] diff --git a/src/courier/types/shared/timeouts.py b/src/courier/types/shared/timeouts.py new file mode 100644 index 00000000..e55b7047 --- /dev/null +++ b/src/courier/types/shared/timeouts.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["Timeouts"] + + +class Timeouts(BaseModel): + channel: Optional[int] = None + + provider: Optional[int] = None diff --git a/src/courier/types/shared/token.py b/src/courier/types/shared/token.py new file mode 100644 index 00000000..ccdade11 --- /dev/null +++ b/src/courier/types/shared/token.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["Token"] + + +class Token(BaseModel): + token: str diff --git a/src/courier/types/shared/user_profile.py b/src/courier/types/shared/user_profile.py new file mode 100644 index 00000000..18138d98 --- /dev/null +++ b/src/courier/types/shared/user_profile.py @@ -0,0 +1,99 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from pydantic import Field as FieldInfo + +from .expo import Expo +from .slack import Slack +from .discord import Discord +from .intercom import Intercom +from .ms_teams import MsTeams +from ..._models import BaseModel +from .airship_profile import AirshipProfile +from .user_profile_firebase_token import UserProfileFirebaseToken + +__all__ = ["UserProfile", "Address"] + + +class Address(BaseModel): + country: str + + formatted: str + + locality: str + + postal_code: str + + region: str + + street_address: str + + +class UserProfile(BaseModel): + address: Optional[Address] = None + + airship: Optional[AirshipProfile] = None + + apn: Optional[str] = None + + birthdate: Optional[str] = None + + custom: Optional[Dict[str, object]] = None + """A free form object. + + Due to a limitation of the API Explorer, you can only enter string key/values + below, but this API accepts more complex object structures. + """ + + discord: Optional[Discord] = None + + email: Optional[str] = None + + email_verified: Optional[bool] = None + + expo: Optional[Expo] = None + + facebook_psid: Optional[str] = FieldInfo(alias="facebookPSID", default=None) + + family_name: Optional[str] = None + + firebase_token: Optional[UserProfileFirebaseToken] = FieldInfo(alias="firebaseToken", default=None) + + gender: Optional[str] = None + + given_name: Optional[str] = None + + intercom: Optional[Intercom] = None + + locale: Optional[str] = None + + middle_name: Optional[str] = None + + ms_teams: Optional[MsTeams] = None + + name: Optional[str] = None + + nickname: Optional[str] = None + + phone_number: Optional[str] = None + + phone_number_verified: Optional[bool] = None + + picture: Optional[str] = None + + preferred_name: Optional[str] = None + + profile: Optional[str] = None + + slack: Optional[Slack] = None + + sub: Optional[str] = None + + target_arn: Optional[str] = None + + updated_at: Optional[str] = None + + website: Optional[str] = None + + zoneinfo: Optional[str] = None diff --git a/src/courier/types/shared/user_profile_firebase_token.py b/src/courier/types/shared/user_profile_firebase_token.py new file mode 100644 index 00000000..dd8e2081 --- /dev/null +++ b/src/courier/types/shared/user_profile_firebase_token.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import TypeAlias + +__all__ = ["UserProfileFirebaseToken"] + +UserProfileFirebaseToken: TypeAlias = Union[str, List[str]] diff --git a/src/courier/types/shared/user_recipient.py b/src/courier/types/shared/user_recipient.py new file mode 100644 index 00000000..236ac2c2 --- /dev/null +++ b/src/courier/types/shared/user_recipient.py @@ -0,0 +1,52 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from pydantic import Field as FieldInfo + +from ..._models import BaseModel +from .preference import Preference +from .message_context import MessageContext + +__all__ = ["UserRecipient", "Preferences"] + + +class Preferences(BaseModel): + notifications: Dict[str, Preference] + + categories: Optional[Dict[str, Preference]] = None + + template_id: Optional[str] = FieldInfo(alias="templateId", default=None) + + +class UserRecipient(BaseModel): + account_id: Optional[str] = None + """Deprecated - Use `tenant_id` instead.""" + + context: Optional[MessageContext] = None + """Context such as tenant_id to send the notification with.""" + + data: Optional[Dict[str, object]] = None + + email: Optional[str] = None + """The user's email address.""" + + list_id: Optional[str] = None + """The id of the list to send the message to.""" + + locale: Optional[str] = None + """The user's preferred ISO 639-1 language code.""" + + phone_number: Optional[str] = None + """The user's phone number.""" + + preferences: Optional[Preferences] = None + + tenant_id: Optional[str] = None + """The id of the tenant the user is associated with.""" + + user_id: Optional[str] = None + """The user's unique identifier. + + Typically, this will match the user id of a user in your system. + """ diff --git a/src/courier/types/shared/utm.py b/src/courier/types/shared/utm.py new file mode 100644 index 00000000..b79e9fe3 --- /dev/null +++ b/src/courier/types/shared/utm.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["Utm"] + + +class Utm(BaseModel): + campaign: Optional[str] = None + + content: Optional[str] = None + + medium: Optional[str] = None + + source: Optional[str] = None + + term: Optional[str] = None diff --git a/src/courier/types/shared/webhook_auth_mode.py b/src/courier/types/shared/webhook_auth_mode.py new file mode 100644 index 00000000..1cdb0add --- /dev/null +++ b/src/courier/types/shared/webhook_auth_mode.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["WebhookAuthMode"] + +WebhookAuthMode: TypeAlias = Literal["none", "basic", "bearer"] diff --git a/src/courier/types/shared/webhook_authentication.py b/src/courier/types/shared/webhook_authentication.py new file mode 100644 index 00000000..0ade6be1 --- /dev/null +++ b/src/courier/types/shared/webhook_authentication.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .webhook_auth_mode import WebhookAuthMode + +__all__ = ["WebhookAuthentication"] + + +class WebhookAuthentication(BaseModel): + mode: WebhookAuthMode + """The authentication mode to use. Defaults to 'none' if not specified.""" + + token: Optional[str] = None + """Token for bearer authentication.""" + + password: Optional[str] = None + """Password for basic authentication.""" + + username: Optional[str] = None + """Username for basic authentication.""" diff --git a/src/courier/types/shared/webhook_method.py b/src/courier/types/shared/webhook_method.py new file mode 100644 index 00000000..566044ba --- /dev/null +++ b/src/courier/types/shared/webhook_method.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["WebhookMethod"] + +WebhookMethod: TypeAlias = Literal["POST", "PUT"] diff --git a/src/courier/types/shared/webhook_profile.py b/src/courier/types/shared/webhook_profile.py new file mode 100644 index 00000000..31778999 --- /dev/null +++ b/src/courier/types/shared/webhook_profile.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from ..._models import BaseModel +from .webhook_method import WebhookMethod +from .webhook_profile_type import WebhookProfileType +from .webhook_authentication import WebhookAuthentication + +__all__ = ["WebhookProfile"] + + +class WebhookProfile(BaseModel): + url: str + """The URL to send the webhook request to.""" + + authentication: Optional[WebhookAuthentication] = None + """Authentication configuration for the webhook request.""" + + headers: Optional[Dict[str, str]] = None + """Custom headers to include in the webhook request.""" + + method: Optional[WebhookMethod] = None + """The HTTP method to use for the webhook request. + + Defaults to POST if not specified. + """ + + profile: Optional[WebhookProfileType] = None + """Specifies what profile information is included in the request payload. + + Defaults to 'limited' if not specified. + """ diff --git a/src/courier/types/shared/webhook_profile_type.py b/src/courier/types/shared/webhook_profile_type.py new file mode 100644 index 00000000..0726b1e1 --- /dev/null +++ b/src/courier/types/shared/webhook_profile_type.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["WebhookProfileType"] + +WebhookProfileType: TypeAlias = Literal["limited", "expanded"] diff --git a/src/courier/types/shared/webhook_recipient.py b/src/courier/types/shared/webhook_recipient.py new file mode 100644 index 00000000..b486ad80 --- /dev/null +++ b/src/courier/types/shared/webhook_recipient.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .webhook_profile import WebhookProfile + +__all__ = ["WebhookRecipient"] + + +class WebhookRecipient(BaseModel): + """Send via webhook""" + + webhook: WebhookProfile diff --git a/src/courier/types/shared_params/__init__.py b/src/courier/types/shared_params/__init__.py new file mode 100644 index 00000000..8ccef58f --- /dev/null +++ b/src/courier/types/shared_params/__init__.py @@ -0,0 +1,61 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .utm import Utm as Utm +from .rule import Rule as Rule +from .slack import Slack as Slack +from .channel import Channel as Channel +from .metadata import Metadata as Metadata +from .ms_teams import MsTeams as MsTeams +from .timeouts import Timeouts as Timeouts +from .pagerduty import Pagerduty as Pagerduty +from .preference import Preference as Preference +from .list_filter import ListFilter as ListFilter +from .filter_config import FilterConfig as FilterConfig +from .elemental_node import ElementalNode as ElementalNode +from .list_recipient import ListRecipient as ListRecipient +from .user_recipient import UserRecipient as UserRecipient +from .webhook_method import WebhookMethod as WebhookMethod +from .audience_filter import AudienceFilter as AudienceFilter +from .message_context import MessageContext as MessageContext +from .message_routing import MessageRouting as MessageRouting +from .slack_recipient import SlackRecipient as SlackRecipient +from .webhook_profile import WebhookProfile as WebhookProfile +from .channel_metadata import ChannelMetadata as ChannelMetadata +from .message_channels import MessageChannels as MessageChannels +from .elemental_content import ElementalContent as ElementalContent +from .message_providers import MessageProviders as MessageProviders +from .preference_status import PreferenceStatus as PreferenceStatus +from .webhook_auth_mode import WebhookAuthMode as WebhookAuthMode +from .webhook_recipient import WebhookRecipient as WebhookRecipient +from .audience_recipient import AudienceRecipient as AudienceRecipient +from .channel_preference import ChannelPreference as ChannelPreference +from .ms_teams_recipient import MsTeamsRecipient as MsTeamsRecipient +from .elemental_base_node import ElementalBaseNode as ElementalBaseNode +from .pagerduty_recipient import PagerdutyRecipient as PagerdutyRecipient +from .send_to_slack_email import SendToSlackEmail as SendToSlackEmail +from .webhook_profile_type import WebhookProfileType as WebhookProfileType +from .recipient_preferences import RecipientPreferences as RecipientPreferences +from .send_to_slack_channel import SendToSlackChannel as SendToSlackChannel +from .send_to_slack_user_id import SendToSlackUserID as SendToSlackUserID +from .audience_filter_config import AudienceFilterConfig as AudienceFilterConfig +from .channel_classification import ChannelClassification as ChannelClassification +from .elemental_channel_node import ElementalChannelNode as ElementalChannelNode +from .list_pattern_recipient import ListPatternRecipient as ListPatternRecipient +from .message_providers_type import MessageProvidersType as MessageProvidersType +from .send_to_ms_teams_email import SendToMsTeamsEmail as SendToMsTeamsEmail +from .webhook_authentication import WebhookAuthentication as WebhookAuthentication +from .elemental_content_sugar import ElementalContentSugar as ElementalContentSugar +from .message_routing_channel import MessageRoutingChannel as MessageRoutingChannel +from .send_to_ms_teams_user_id import SendToMsTeamsUserID as SendToMsTeamsUserID +from .send_to_ms_teams_channel_id import SendToMsTeamsChannelID as SendToMsTeamsChannelID +from .elemental_html_node_with_type import ElementalHTMLNodeWithType as ElementalHTMLNodeWithType +from .elemental_meta_node_with_type import ElementalMetaNodeWithType as ElementalMetaNodeWithType +from .elemental_text_node_with_type import ElementalTextNodeWithType as ElementalTextNodeWithType +from .send_to_ms_teams_channel_name import SendToMsTeamsChannelName as SendToMsTeamsChannelName +from .elemental_image_node_with_type import ElementalImageNodeWithType as ElementalImageNodeWithType +from .elemental_quote_node_with_type import ElementalQuoteNodeWithType as ElementalQuoteNodeWithType +from .elemental_action_node_with_type import ElementalActionNodeWithType as ElementalActionNodeWithType +from .notification_preference_details import NotificationPreferenceDetails as NotificationPreferenceDetails +from .elemental_channel_node_with_type import ElementalChannelNodeWithType as ElementalChannelNodeWithType +from .elemental_divider_node_with_type import ElementalDividerNodeWithType as ElementalDividerNodeWithType +from .send_to_ms_teams_conversation_id import SendToMsTeamsConversationID as SendToMsTeamsConversationID diff --git a/src/courier/types/shared_params/audience_filter.py b/src/courier/types/shared_params/audience_filter.py new file mode 100644 index 00000000..401bcc27 --- /dev/null +++ b/src/courier/types/shared_params/audience_filter.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["AudienceFilter"] + + +class AudienceFilter(TypedDict, total=False): + operator: Required[Literal["MEMBER_OF"]] + """Send to users only if they are member of the account""" + + path: Required[Literal["account_id"]] + + value: Required[str] diff --git a/src/courier/types/shared_params/audience_filter_config.py b/src/courier/types/shared_params/audience_filter_config.py new file mode 100644 index 00000000..fc701e1c --- /dev/null +++ b/src/courier/types/shared_params/audience_filter_config.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["AudienceFilterConfig"] + + +class AudienceFilterConfig(TypedDict, total=False): + """ + Filter configuration for audience membership containing an array of filter rules + """ + + filters: Required[Iterable["FilterConfig"]] + """Array of filter rules (single conditions or nested groups)""" + + operator: Literal["AND", "OR"] + """The logical operator (AND/OR) combining the rules in `filters`. + + Required when `filters` contains more than one rule. If omitted, the top-level + `operator` field on the request is used instead. + """ + + +from .filter_config import FilterConfig diff --git a/src/courier/types/shared_params/audience_recipient.py b/src/courier/types/shared_params/audience_recipient.py new file mode 100644 index 00000000..dbea54bb --- /dev/null +++ b/src/courier/types/shared_params/audience_recipient.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Iterable, Optional +from typing_extensions import Required, TypedDict + +from .audience_filter import AudienceFilter + +__all__ = ["AudienceRecipient"] + + +class AudienceRecipient(TypedDict, total=False): + """Send to all users in an audience""" + + audience_id: Required[str] + """A unique identifier associated with an Audience. + + A message will be sent to each user in the audience. + """ + + data: Optional[Dict[str, object]] + + filters: Optional[Iterable[AudienceFilter]] diff --git a/src/courier/types/shared_params/channel.py b/src/courier/types/shared_params/channel.py new file mode 100644 index 00000000..e83d67c9 --- /dev/null +++ b/src/courier/types/shared_params/channel.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, TypedDict + +from ..._types import SequenceNotStr +from .timeouts import Timeouts +from .channel_metadata import ChannelMetadata + +__all__ = ["Channel"] + +_ChannelReservedKeywords = TypedDict( + "_ChannelReservedKeywords", + { + "if": Optional[str], + }, + total=False, +) + + +class Channel(_ChannelReservedKeywords, total=False): + brand_id: Optional[str] + """Brand id used for rendering.""" + + metadata: Optional[ChannelMetadata] + + override: Optional[Dict[str, object]] + """Channel specific overrides.""" + + providers: Optional[SequenceNotStr[str]] + """Providers enabled for this channel.""" + + routing_method: Optional[Literal["all", "single"]] + """Defaults to `single`.""" + + timeouts: Optional[Timeouts] diff --git a/src/courier/types/shared_params/channel_classification.py b/src/courier/types/shared_params/channel_classification.py new file mode 100644 index 00000000..b9810ef6 --- /dev/null +++ b/src/courier/types/shared_params/channel_classification.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ChannelClassification"] + +ChannelClassification: TypeAlias = Literal["direct_message", "email", "push", "sms", "webhook", "inbox"] diff --git a/src/courier/types/shared_params/channel_metadata.py b/src/courier/types/shared_params/channel_metadata.py new file mode 100644 index 00000000..7238b7c2 --- /dev/null +++ b/src/courier/types/shared_params/channel_metadata.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +from .utm import Utm + +__all__ = ["ChannelMetadata"] + + +class ChannelMetadata(TypedDict, total=False): + utm: Optional[Utm] diff --git a/src/courier/types/shared_params/channel_preference.py b/src/courier/types/shared_params/channel_preference.py new file mode 100644 index 00000000..033ee000 --- /dev/null +++ b/src/courier/types/shared_params/channel_preference.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from ..shared.channel_classification import ChannelClassification + +__all__ = ["ChannelPreference"] + + +class ChannelPreference(TypedDict, total=False): + channel: Required[ChannelClassification] diff --git a/src/courier/types/shared_params/elemental_action_node_with_type.py b/src/courier/types/shared_params/elemental_action_node_with_type.py new file mode 100644 index 00000000..5be216ca --- /dev/null +++ b/src/courier/types/shared_params/elemental_action_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalActionNodeWithType"] + + +class ElementalActionNodeWithType(ElementalBaseNode, total=False): + type: Literal["action"] diff --git a/src/courier/types/shared_params/elemental_base_node.py b/src/courier/types/shared_params/elemental_base_node.py new file mode 100644 index 00000000..b0283611 --- /dev/null +++ b/src/courier/types/shared_params/elemental_base_node.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["ElementalBaseNode"] + +_ElementalBaseNodeReservedKeywords = TypedDict( + "_ElementalBaseNodeReservedKeywords", + { + "if": Optional[str], + }, + total=False, +) + + +class ElementalBaseNode(_ElementalBaseNodeReservedKeywords, total=False): + channels: Optional[SequenceNotStr[str]] + + loop: Optional[str] + + ref: Optional[str] diff --git a/src/courier/types/shared_params/elemental_channel_node.py b/src/courier/types/shared_params/elemental_channel_node.py new file mode 100644 index 00000000..e26c8aed --- /dev/null +++ b/src/courier/types/shared_params/elemental_channel_node.py @@ -0,0 +1,56 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalChannelNode"] + + +class ElementalChannelNode(ElementalBaseNode, total=False): + """ + The channel element allows a notification to be customized based on which channel it is sent through. + For example, you may want to display a detailed message when the notification is sent through email, + and a more concise message in a push notification. Channel elements are only valid as top-level + elements; you cannot nest channel elements. If there is a channel element specified at the top-level + of the document, all sibling elements must be channel elements. + Note: As an alternative, most elements support a `channel` property. Which allows you to selectively + display an individual element on a per channel basis. See the + [control flow docs](https://www.courier.com/docs/platform/content/elemental/control-flow/) for more details. + """ + + channel: str + """The channel the contents of this element should be applied to. + + Can be `email`, `push`, `direct_message`, `sms` or a provider such as slack + """ + + font_size: Optional[str] + """Email only. + + Document-level base font size (CSS px, e.g. `16px`) for body content — text, + quote, list and action button labels. Heading styles (`h1`/`h2`/`h3`) and + `subtext` keep their preset sizes. + """ + + line_height: Optional[str] + """Email only. + + Document-level line height (CSS px or unitless multiplier, e.g. `24px` or `1.5`) + applied to all body content unless overridden per block. + """ + + padding: Optional[str] + """Email only. + + Document-level body padding applied once around the email body, as a CSS px + shorthand (1–4 values), e.g. `48px 64px`. + """ + + raw: Optional[Dict[str, object]] + """Raw data to apply to the channel. + + If `elements` has not been specified, `raw` is required. + """ diff --git a/src/courier/types/shared_params/elemental_channel_node_with_type.py b/src/courier/types/shared_params/elemental_channel_node_with_type.py new file mode 100644 index 00000000..777b0210 --- /dev/null +++ b/src/courier/types/shared_params/elemental_channel_node_with_type.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_channel_node import ElementalChannelNode + +__all__ = ["ElementalChannelNodeWithType"] + + +class ElementalChannelNodeWithType(ElementalChannelNode, total=False): + """ + The channel element allows a notification to be customized based on which channel it is sent through. + For example, you may want to display a detailed message when the notification is sent through email, + and a more concise message in a push notification. Channel elements are only valid as top-level + elements; you cannot nest channel elements. If there is a channel element specified at the top-level + of the document, all sibling elements must be channel elements. + Note: As an alternative, most elements support a `channel` property. Which allows you to selectively + display an individual element on a per channel basis. See the + [control flow docs](https://www.courier.com/docs/platform/content/elemental/control-flow/) for more details. + """ + + type: Literal["channel"] diff --git a/src/courier/types/shared_params/elemental_content.py b/src/courier/types/shared_params/elemental_content.py new file mode 100644 index 00000000..8e57dbe0 --- /dev/null +++ b/src/courier/types/shared_params/elemental_content.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from .elemental_node import ElementalNode + +__all__ = ["ElementalContent"] + + +class ElementalContent(TypedDict, total=False): + elements: Required[Iterable[ElementalNode]] + + version: Required[str] + """For example, "2022-01-01" """ diff --git a/src/courier/types/shared_params/elemental_content_sugar.py b/src/courier/types/shared_params/elemental_content_sugar.py new file mode 100644 index 00000000..eb9e0232 --- /dev/null +++ b/src/courier/types/shared_params/elemental_content_sugar.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["ElementalContentSugar"] + + +class ElementalContentSugar(TypedDict, total=False): + """Syntactic sugar to provide a fast shorthand for Courier Elemental Blocks.""" + + body: Required[str] + """The text content displayed in the notification.""" + + title: Required[str] + """Title/subject displayed by supported channels.""" diff --git a/src/courier/types/shared_params/elemental_divider_node_with_type.py b/src/courier/types/shared_params/elemental_divider_node_with_type.py new file mode 100644 index 00000000..67cc64e3 --- /dev/null +++ b/src/courier/types/shared_params/elemental_divider_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalDividerNodeWithType"] + + +class ElementalDividerNodeWithType(ElementalBaseNode, total=False): + type: Literal["divider"] diff --git a/src/courier/types/shared_params/elemental_html_node_with_type.py b/src/courier/types/shared_params/elemental_html_node_with_type.py new file mode 100644 index 00000000..65f5fab4 --- /dev/null +++ b/src/courier/types/shared_params/elemental_html_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalHTMLNodeWithType"] + + +class ElementalHTMLNodeWithType(ElementalBaseNode, total=False): + type: Literal["html"] diff --git a/src/courier/types/shared_params/elemental_image_node_with_type.py b/src/courier/types/shared_params/elemental_image_node_with_type.py new file mode 100644 index 00000000..2f2a0f9b --- /dev/null +++ b/src/courier/types/shared_params/elemental_image_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalImageNodeWithType"] + + +class ElementalImageNodeWithType(ElementalBaseNode, total=False): + type: Literal["image"] diff --git a/src/courier/types/shared_params/elemental_meta_node_with_type.py b/src/courier/types/shared_params/elemental_meta_node_with_type.py new file mode 100644 index 00000000..c7ae4c16 --- /dev/null +++ b/src/courier/types/shared_params/elemental_meta_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalMetaNodeWithType"] + + +class ElementalMetaNodeWithType(ElementalBaseNode, total=False): + type: Literal["meta"] diff --git a/src/courier/types/shared_params/elemental_node.py b/src/courier/types/shared_params/elemental_node.py new file mode 100644 index 00000000..0db24ba0 --- /dev/null +++ b/src/courier/types/shared_params/elemental_node.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .elemental_html_node_with_type import ElementalHTMLNodeWithType +from .elemental_meta_node_with_type import ElementalMetaNodeWithType +from .elemental_text_node_with_type import ElementalTextNodeWithType +from .elemental_image_node_with_type import ElementalImageNodeWithType +from .elemental_quote_node_with_type import ElementalQuoteNodeWithType +from .elemental_action_node_with_type import ElementalActionNodeWithType +from .elemental_channel_node_with_type import ElementalChannelNodeWithType +from .elemental_divider_node_with_type import ElementalDividerNodeWithType + +__all__ = ["ElementalNode"] + +ElementalNode: TypeAlias = Union[ + ElementalTextNodeWithType, + ElementalMetaNodeWithType, + ElementalChannelNodeWithType, + ElementalImageNodeWithType, + ElementalActionNodeWithType, + ElementalDividerNodeWithType, + ElementalQuoteNodeWithType, + ElementalHTMLNodeWithType, +] diff --git a/src/courier/types/shared_params/elemental_quote_node_with_type.py b/src/courier/types/shared_params/elemental_quote_node_with_type.py new file mode 100644 index 00000000..de0ea248 --- /dev/null +++ b/src/courier/types/shared_params/elemental_quote_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalQuoteNodeWithType"] + + +class ElementalQuoteNodeWithType(ElementalBaseNode, total=False): + type: Literal["quote"] diff --git a/src/courier/types/shared_params/elemental_text_node_with_type.py b/src/courier/types/shared_params/elemental_text_node_with_type.py new file mode 100644 index 00000000..ffd8940e --- /dev/null +++ b/src/courier/types/shared_params/elemental_text_node_with_type.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +from .elemental_base_node import ElementalBaseNode + +__all__ = ["ElementalTextNodeWithType"] + + +class ElementalTextNodeWithType(ElementalBaseNode, total=False): + type: Literal["text"] diff --git a/src/courier/types/shared_params/filter_config.py b/src/courier/types/shared_params/filter_config.py new file mode 100644 index 00000000..616e2f37 --- /dev/null +++ b/src/courier/types/shared_params/filter_config.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +__all__ = ["FilterConfig"] + + +class FilterConfig(TypedDict, total=False): + """ + A filter rule that can be either a single condition (with path/value) or a nested group (with filters array). Use comparison operators (EQ, GT, etc.) for single conditions, and logical operators (AND, OR) for nested groups. + """ + + operator: Required[str] + """The operator for this filter. + + Use comparison operators (EQ, GT, LT, GTE, LTE, NEQ, EXISTS, INCLUDES, + STARTS_WITH, ENDS_WITH, IS_BEFORE, IS_AFTER, OMIT) for single conditions, or + logical operators (AND, OR) for nested filter groups. + """ + + filters: Iterable["FilterConfig"] + """Nested filter rules to combine with AND/OR. + + Required for nested filter groups, not used for single filter conditions. + """ + + path: str + """The attribute path from the user profile to filter on. + + Required for single filter conditions, not used for nested filter groups. + """ + + value: str + """The value to compare against. + + Required for single filter conditions, not used for nested filter groups. + """ diff --git a/src/courier/types/shared_params/list_filter.py b/src/courier/types/shared_params/list_filter.py new file mode 100644 index 00000000..2c798cf6 --- /dev/null +++ b/src/courier/types/shared_params/list_filter.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ListFilter"] + + +class ListFilter(TypedDict, total=False): + operator: Required[Literal["MEMBER_OF"]] + """Send to users only if they are member of the account""" + + path: Required[Literal["account_id"]] + + value: Required[str] diff --git a/src/courier/types/shared_params/list_pattern_recipient.py b/src/courier/types/shared_params/list_pattern_recipient.py new file mode 100644 index 00000000..25aeec22 --- /dev/null +++ b/src/courier/types/shared_params/list_pattern_recipient.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import TypedDict + +__all__ = ["ListPatternRecipient"] + + +class ListPatternRecipient(TypedDict, total=False): + """Send to users in lists matching a pattern""" + + data: Optional[Dict[str, object]] + + list_pattern: Optional[str] diff --git a/src/courier/types/shared_params/list_recipient.py b/src/courier/types/shared_params/list_recipient.py new file mode 100644 index 00000000..aed51abd --- /dev/null +++ b/src/courier/types/shared_params/list_recipient.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Iterable, Optional +from typing_extensions import TypedDict + +from .list_filter import ListFilter + +__all__ = ["ListRecipient"] + + +class ListRecipient(TypedDict, total=False): + """Send to all users in a specific list""" + + data: Optional[Dict[str, object]] + + filters: Optional[Iterable[ListFilter]] + + list_id: Optional[str] diff --git a/src/courier/types/shared_params/message_channels.py b/src/courier/types/shared_params/message_channels.py new file mode 100644 index 00000000..d71025da --- /dev/null +++ b/src/courier/types/shared_params/message_channels.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import TypeAlias + +from .channel import Channel + +__all__ = ["MessageChannels"] + +MessageChannels: TypeAlias = Dict[str, Channel] diff --git a/src/courier/types/shared_params/message_context.py b/src/courier/types/shared_params/message_context.py new file mode 100644 index 00000000..b2e6bbbb --- /dev/null +++ b/src/courier/types/shared_params/message_context.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["MessageContext"] + + +class MessageContext(TypedDict, total=False): + tenant_id: Optional[str] + """Tenant id used to load brand/default preferences/context.""" diff --git a/src/courier/types/shared_params/message_providers.py b/src/courier/types/shared_params/message_providers.py new file mode 100644 index 00000000..73704fa0 --- /dev/null +++ b/src/courier/types/shared_params/message_providers.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import TypeAlias + +from .message_providers_type import MessageProvidersType + +__all__ = ["MessageProviders"] + +MessageProviders: TypeAlias = Dict[str, MessageProvidersType] diff --git a/src/courier/types/shared_params/message_providers_type.py b/src/courier/types/shared_params/message_providers_type.py new file mode 100644 index 00000000..aa457e79 --- /dev/null +++ b/src/courier/types/shared_params/message_providers_type.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import TypedDict + +from .metadata import Metadata + +__all__ = ["MessageProvidersType"] + +_MessageProvidersTypeReservedKeywords = TypedDict( + "_MessageProvidersTypeReservedKeywords", + { + "if": Optional[str], + }, + total=False, +) + + +class MessageProvidersType(_MessageProvidersTypeReservedKeywords, total=False): + metadata: Optional[Metadata] + + override: Optional[Dict[str, object]] + """Provider-specific overrides.""" + + timeouts: Optional[int] diff --git a/src/courier/types/shared_params/message_routing.py b/src/courier/types/shared_params/message_routing.py new file mode 100644 index 00000000..6bd00c91 --- /dev/null +++ b/src/courier/types/shared_params/message_routing.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from ..._types import SequenceNotStr + +__all__ = ["MessageRouting"] + + +class MessageRouting(TypedDict, total=False): + channels: Required[SequenceNotStr["MessageRoutingChannel"]] + + method: Required[Literal["all", "single"]] + + +from .message_routing_channel import MessageRoutingChannel diff --git a/src/courier/types/shared_params/message_routing_channel.py b/src/courier/types/shared_params/message_routing_channel.py new file mode 100644 index 00000000..0183c4a1 --- /dev/null +++ b/src/courier/types/shared_params/message_routing_channel.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Union +from typing_extensions import TypeAlias, TypeAliasType + +from ..._compat import PYDANTIC_V1 + +__all__ = ["MessageRoutingChannel"] + +if TYPE_CHECKING or not PYDANTIC_V1: + MessageRoutingChannel = TypeAliasType("MessageRoutingChannel", Union[str, "MessageRouting"]) +else: + MessageRoutingChannel: TypeAlias = Union[str, "MessageRouting"] + +from .message_routing import MessageRouting diff --git a/src/courier/types/shared_params/metadata.py b/src/courier/types/shared_params/metadata.py new file mode 100644 index 00000000..38362bdd --- /dev/null +++ b/src/courier/types/shared_params/metadata.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +from .utm import Utm + +__all__ = ["Metadata"] + + +class Metadata(TypedDict, total=False): + utm: Optional[Utm] diff --git a/src/courier/types/shared_params/ms_teams.py b/src/courier/types/shared_params/ms_teams.py new file mode 100644 index 00000000..876fc346 --- /dev/null +++ b/src/courier/types/shared_params/ms_teams.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .send_to_ms_teams_email import SendToMsTeamsEmail +from .send_to_ms_teams_user_id import SendToMsTeamsUserID +from .send_to_ms_teams_channel_id import SendToMsTeamsChannelID +from .send_to_ms_teams_channel_name import SendToMsTeamsChannelName +from .send_to_ms_teams_conversation_id import SendToMsTeamsConversationID + +__all__ = ["MsTeams"] + +MsTeams: TypeAlias = Union[ + SendToMsTeamsUserID, + SendToMsTeamsEmail, + SendToMsTeamsChannelID, + SendToMsTeamsConversationID, + SendToMsTeamsChannelName, +] diff --git a/src/courier/types/shared_params/ms_teams_recipient.py b/src/courier/types/shared_params/ms_teams_recipient.py new file mode 100644 index 00000000..4dd36ecb --- /dev/null +++ b/src/courier/types/shared_params/ms_teams_recipient.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .ms_teams import MsTeams + +__all__ = ["MsTeamsRecipient"] + + +class MsTeamsRecipient(TypedDict, total=False): + """Send via Microsoft Teams""" + + ms_teams: Required[MsTeams] diff --git a/src/courier/types/shared_params/notification_preference_details.py b/src/courier/types/shared_params/notification_preference_details.py new file mode 100644 index 00000000..0026095f --- /dev/null +++ b/src/courier/types/shared_params/notification_preference_details.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Required, TypedDict + +from .rule import Rule +from .channel_preference import ChannelPreference +from ..shared.preference_status import PreferenceStatus + +__all__ = ["NotificationPreferenceDetails"] + + +class NotificationPreferenceDetails(TypedDict, total=False): + status: Required[PreferenceStatus] + + channel_preferences: Optional[Iterable[ChannelPreference]] + + rules: Optional[Iterable[Rule]] diff --git a/src/courier/types/shared_params/pagerduty.py b/src/courier/types/shared_params/pagerduty.py new file mode 100644 index 00000000..20456662 --- /dev/null +++ b/src/courier/types/shared_params/pagerduty.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["Pagerduty"] + + +class Pagerduty(TypedDict, total=False): + event_action: Optional[str] + + routing_key: Optional[str] + + severity: Optional[str] + + source: Optional[str] diff --git a/src/courier/types/shared_params/pagerduty_recipient.py b/src/courier/types/shared_params/pagerduty_recipient.py new file mode 100644 index 00000000..131145bc --- /dev/null +++ b/src/courier/types/shared_params/pagerduty_recipient.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .pagerduty import Pagerduty + +__all__ = ["PagerdutyRecipient"] + + +class PagerdutyRecipient(TypedDict, total=False): + """Send via PagerDuty""" + + pagerduty: Required[Pagerduty] diff --git a/src/courier/types/shared_params/preference.py b/src/courier/types/shared_params/preference.py new file mode 100644 index 00000000..f149e653 --- /dev/null +++ b/src/courier/types/shared_params/preference.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .rule import Rule +from .channel_preference import ChannelPreference +from ..shared.preference_status import PreferenceStatus + +__all__ = ["Preference"] + + +class Preference(TypedDict, total=False): + status: Required[PreferenceStatus] + + channel_preferences: Optional[Iterable[ChannelPreference]] + + rules: Optional[Iterable[Rule]] + + source: Optional[Literal["subscription", "list", "recipient"]] diff --git a/src/courier/types/shared_params/preference_status.py b/src/courier/types/shared_params/preference_status.py new file mode 100644 index 00000000..a4b0f830 --- /dev/null +++ b/src/courier/types/shared_params/preference_status.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypeAlias + +__all__ = ["PreferenceStatus"] + +PreferenceStatus: TypeAlias = Literal["OPTED_IN", "OPTED_OUT", "REQUIRED"] diff --git a/src/courier/types/shared_params/recipient_preferences.py b/src/courier/types/shared_params/recipient_preferences.py new file mode 100644 index 00000000..4f9c0392 --- /dev/null +++ b/src/courier/types/shared_params/recipient_preferences.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import TypedDict + +from .notification_preference_details import NotificationPreferenceDetails + +__all__ = ["RecipientPreferences"] + + +class RecipientPreferences(TypedDict, total=False): + categories: Optional[Dict[str, NotificationPreferenceDetails]] + + notifications: Optional[Dict[str, NotificationPreferenceDetails]] diff --git a/src/courier/types/shared_params/rule.py b/src/courier/types/shared_params/rule.py new file mode 100644 index 00000000..8af43d6d --- /dev/null +++ b/src/courier/types/shared_params/rule.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +__all__ = ["Rule"] + + +class Rule(TypedDict, total=False): + until: Required[str] + + start: Optional[str] diff --git a/src/courier/types/shared_params/send_to_ms_teams_channel_id.py b/src/courier/types/shared_params/send_to_ms_teams_channel_id.py new file mode 100644 index 00000000..60b130dd --- /dev/null +++ b/src/courier/types/shared_params/send_to_ms_teams_channel_id.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToMsTeamsChannelID"] + + +class SendToMsTeamsChannelID(TypedDict, total=False): + channel_id: Required[str] + + service_url: Required[str] + + tenant_id: Required[str] diff --git a/src/courier/types/shared_params/send_to_ms_teams_channel_name.py b/src/courier/types/shared_params/send_to_ms_teams_channel_name.py new file mode 100644 index 00000000..d39854e5 --- /dev/null +++ b/src/courier/types/shared_params/send_to_ms_teams_channel_name.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToMsTeamsChannelName"] + + +class SendToMsTeamsChannelName(TypedDict, total=False): + channel_name: Required[str] + + service_url: Required[str] + + team_id: Required[str] + + tenant_id: Required[str] diff --git a/src/courier/types/shared_params/send_to_ms_teams_conversation_id.py b/src/courier/types/shared_params/send_to_ms_teams_conversation_id.py new file mode 100644 index 00000000..187335cd --- /dev/null +++ b/src/courier/types/shared_params/send_to_ms_teams_conversation_id.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToMsTeamsConversationID"] + + +class SendToMsTeamsConversationID(TypedDict, total=False): + conversation_id: Required[str] + + service_url: Required[str] + + tenant_id: Required[str] diff --git a/src/courier/types/shared_params/send_to_ms_teams_email.py b/src/courier/types/shared_params/send_to_ms_teams_email.py new file mode 100644 index 00000000..6bc5cb4b --- /dev/null +++ b/src/courier/types/shared_params/send_to_ms_teams_email.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToMsTeamsEmail"] + + +class SendToMsTeamsEmail(TypedDict, total=False): + email: Required[str] + + service_url: Required[str] + + tenant_id: Required[str] diff --git a/src/courier/types/shared_params/send_to_ms_teams_user_id.py b/src/courier/types/shared_params/send_to_ms_teams_user_id.py new file mode 100644 index 00000000..43e374dc --- /dev/null +++ b/src/courier/types/shared_params/send_to_ms_teams_user_id.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToMsTeamsUserID"] + + +class SendToMsTeamsUserID(TypedDict, total=False): + service_url: Required[str] + + tenant_id: Required[str] + + user_id: Required[str] diff --git a/src/courier/types/shared_params/send_to_slack_channel.py b/src/courier/types/shared_params/send_to_slack_channel.py new file mode 100644 index 00000000..783058fb --- /dev/null +++ b/src/courier/types/shared_params/send_to_slack_channel.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToSlackChannel"] + + +class SendToSlackChannel(TypedDict, total=False): + access_token: Required[str] + + channel: Required[str] diff --git a/src/courier/types/shared_params/send_to_slack_email.py b/src/courier/types/shared_params/send_to_slack_email.py new file mode 100644 index 00000000..626ab3d2 --- /dev/null +++ b/src/courier/types/shared_params/send_to_slack_email.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToSlackEmail"] + + +class SendToSlackEmail(TypedDict, total=False): + access_token: Required[str] + + email: Required[str] diff --git a/src/courier/types/shared_params/send_to_slack_user_id.py b/src/courier/types/shared_params/send_to_slack_user_id.py new file mode 100644 index 00000000..81af0b34 --- /dev/null +++ b/src/courier/types/shared_params/send_to_slack_user_id.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["SendToSlackUserID"] + + +class SendToSlackUserID(TypedDict, total=False): + access_token: Required[str] + + user_id: Required[str] diff --git a/src/courier/types/shared_params/slack.py b/src/courier/types/shared_params/slack.py new file mode 100644 index 00000000..a34e5c52 --- /dev/null +++ b/src/courier/types/shared_params/slack.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .send_to_slack_email import SendToSlackEmail +from .send_to_slack_channel import SendToSlackChannel +from .send_to_slack_user_id import SendToSlackUserID + +__all__ = ["Slack"] + +Slack: TypeAlias = Union[SendToSlackChannel, SendToSlackEmail, SendToSlackUserID] diff --git a/src/courier/types/shared_params/slack_recipient.py b/src/courier/types/shared_params/slack_recipient.py new file mode 100644 index 00000000..607c7b0d --- /dev/null +++ b/src/courier/types/shared_params/slack_recipient.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .slack import Slack + +__all__ = ["SlackRecipient"] + + +class SlackRecipient(TypedDict, total=False): + """Send via Slack (channel, email, or user_id)""" + + slack: Required[Slack] diff --git a/src/courier/types/shared_params/timeouts.py b/src/courier/types/shared_params/timeouts.py new file mode 100644 index 00000000..32d8f538 --- /dev/null +++ b/src/courier/types/shared_params/timeouts.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["Timeouts"] + + +class Timeouts(TypedDict, total=False): + channel: Optional[int] + + provider: Optional[int] diff --git a/src/courier/types/shared_params/user_recipient.py b/src/courier/types/shared_params/user_recipient.py new file mode 100644 index 00000000..f75f76f8 --- /dev/null +++ b/src/courier/types/shared_params/user_recipient.py @@ -0,0 +1,53 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from .preference import Preference +from .message_context import MessageContext + +__all__ = ["UserRecipient", "Preferences"] + + +class Preferences(TypedDict, total=False): + notifications: Required[Dict[str, Preference]] + + categories: Optional[Dict[str, Preference]] + + template_id: Annotated[Optional[str], PropertyInfo(alias="templateId")] + + +class UserRecipient(TypedDict, total=False): + account_id: Optional[str] + """Deprecated - Use `tenant_id` instead.""" + + context: Optional[MessageContext] + """Context such as tenant_id to send the notification with.""" + + data: Optional[Dict[str, object]] + + email: Optional[str] + """The user's email address.""" + + list_id: Optional[str] + """The id of the list to send the message to.""" + + locale: Optional[str] + """The user's preferred ISO 639-1 language code.""" + + phone_number: Optional[str] + """The user's phone number.""" + + preferences: Optional[Preferences] + + tenant_id: Optional[str] + """The id of the tenant the user is associated with.""" + + user_id: Optional[str] + """The user's unique identifier. + + Typically, this will match the user id of a user in your system. + """ diff --git a/src/courier/types/shared_params/utm.py b/src/courier/types/shared_params/utm.py new file mode 100644 index 00000000..71bfd57a --- /dev/null +++ b/src/courier/types/shared_params/utm.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["Utm"] + + +class Utm(TypedDict, total=False): + campaign: Optional[str] + + content: Optional[str] + + medium: Optional[str] + + source: Optional[str] + + term: Optional[str] diff --git a/src/courier/types/shared_params/webhook_auth_mode.py b/src/courier/types/shared_params/webhook_auth_mode.py new file mode 100644 index 00000000..c813e2b3 --- /dev/null +++ b/src/courier/types/shared_params/webhook_auth_mode.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypeAlias + +__all__ = ["WebhookAuthMode"] + +WebhookAuthMode: TypeAlias = Literal["none", "basic", "bearer"] diff --git a/src/courier/types/shared_params/webhook_authentication.py b/src/courier/types/shared_params/webhook_authentication.py new file mode 100644 index 00000000..850471a3 --- /dev/null +++ b/src/courier/types/shared_params/webhook_authentication.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from ..shared.webhook_auth_mode import WebhookAuthMode + +__all__ = ["WebhookAuthentication"] + + +class WebhookAuthentication(TypedDict, total=False): + mode: Required[WebhookAuthMode] + """The authentication mode to use. Defaults to 'none' if not specified.""" + + token: Optional[str] + """Token for bearer authentication.""" + + password: Optional[str] + """Password for basic authentication.""" + + username: Optional[str] + """Username for basic authentication.""" diff --git a/src/courier/types/shared_params/webhook_method.py b/src/courier/types/shared_params/webhook_method.py new file mode 100644 index 00000000..08d334d2 --- /dev/null +++ b/src/courier/types/shared_params/webhook_method.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypeAlias + +__all__ = ["WebhookMethod"] + +WebhookMethod: TypeAlias = Literal["POST", "PUT"] diff --git a/src/courier/types/shared_params/webhook_profile.py b/src/courier/types/shared_params/webhook_profile.py new file mode 100644 index 00000000..5880401c --- /dev/null +++ b/src/courier/types/shared_params/webhook_profile.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Required, TypedDict + +from ..shared.webhook_method import WebhookMethod +from .webhook_authentication import WebhookAuthentication +from ..shared.webhook_profile_type import WebhookProfileType + +__all__ = ["WebhookProfile"] + + +class WebhookProfile(TypedDict, total=False): + url: Required[str] + """The URL to send the webhook request to.""" + + authentication: Optional[WebhookAuthentication] + """Authentication configuration for the webhook request.""" + + headers: Optional[Dict[str, str]] + """Custom headers to include in the webhook request.""" + + method: Optional[WebhookMethod] + """The HTTP method to use for the webhook request. + + Defaults to POST if not specified. + """ + + profile: Optional[WebhookProfileType] + """Specifies what profile information is included in the request payload. + + Defaults to 'limited' if not specified. + """ diff --git a/src/courier/types/shared_params/webhook_profile_type.py b/src/courier/types/shared_params/webhook_profile_type.py new file mode 100644 index 00000000..4501442a --- /dev/null +++ b/src/courier/types/shared_params/webhook_profile_type.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypeAlias + +__all__ = ["WebhookProfileType"] + +WebhookProfileType: TypeAlias = Literal["limited", "expanded"] diff --git a/src/courier/types/shared_params/webhook_recipient.py b/src/courier/types/shared_params/webhook_recipient.py new file mode 100644 index 00000000..60c3d1f8 --- /dev/null +++ b/src/courier/types/shared_params/webhook_recipient.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .webhook_profile import WebhookProfile + +__all__ = ["WebhookRecipient"] + + +class WebhookRecipient(TypedDict, total=False): + """Send via webhook""" + + webhook: Required[WebhookProfile] diff --git a/src/courier/types/subscribe_to_lists_request_item_param.py b/src/courier/types/subscribe_to_lists_request_item_param.py new file mode 100644 index 00000000..a97fca5a --- /dev/null +++ b/src/courier/types/subscribe_to_lists_request_item_param.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .shared_params.recipient_preferences import RecipientPreferences + +__all__ = ["SubscribeToListsRequestItemParam"] + + +class SubscribeToListsRequestItemParam(TypedDict, total=False): + list_id: Required[Annotated[str, PropertyInfo(alias="listId")]] + + preferences: Optional[RecipientPreferences] diff --git a/src/courier/types/subscription_list.py b/src/courier/types/subscription_list.py new file mode 100644 index 00000000..99d36859 --- /dev/null +++ b/src/courier/types/subscription_list.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["SubscriptionList"] + + +class SubscriptionList(BaseModel): + id: str + + name: str + + created: Optional[str] = None + + updated: Optional[str] = None diff --git a/src/courier/types/subscription_topic_new.py b/src/courier/types/subscription_topic_new.py new file mode 100644 index 00000000..4b4cba2f --- /dev/null +++ b/src/courier/types/subscription_topic_new.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .shared.channel_classification import ChannelClassification + +__all__ = ["SubscriptionTopicNew"] + + +class SubscriptionTopicNew(BaseModel): + status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"] + + custom_routing: Optional[List[ChannelClassification]] = None + """The default channels to send to this tenant when has_custom_routing is enabled""" + + has_custom_routing: Optional[bool] = None + """Override channel routing with custom preferences. + + This will override any template preferences that are set, but a user can still + customize their preferences + """ diff --git a/src/courier/types/subscription_topic_new_param.py b/src/courier/types/subscription_topic_new_param.py new file mode 100644 index 00000000..f7fe329f --- /dev/null +++ b/src/courier/types/subscription_topic_new_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .shared.channel_classification import ChannelClassification + +__all__ = ["SubscriptionTopicNewParam"] + + +class SubscriptionTopicNewParam(TypedDict, total=False): + status: Required[Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"]] + + custom_routing: Optional[List[ChannelClassification]] + """The default channels to send to this tenant when has_custom_routing is enabled""" + + has_custom_routing: Optional[bool] + """Override channel routing with custom preferences. + + This will override any template preferences that are set, but a user can still + customize their preferences + """ diff --git a/src/courier/types/tenant.py b/src/courier/types/tenant.py new file mode 100644 index 00000000..11689329 --- /dev/null +++ b/src/courier/types/tenant.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from .._models import BaseModel +from .default_preferences import DefaultPreferences + +__all__ = ["Tenant"] + + +class Tenant(BaseModel): + id: str + """Id of the tenant.""" + + name: str + """Name of the tenant.""" + + brand_id: Optional[str] = None + """Brand to be used for the account when one is not specified by the send call.""" + + default_preferences: Optional[DefaultPreferences] = None + """ + Defines the preferences used for the account when the user hasn't specified + their own. + """ + + parent_tenant_id: Optional[str] = None + """Tenant's parent id (if any).""" + + properties: Optional[Dict[str, object]] = None + """Arbitrary properties accessible to a template.""" + + user_profile: Optional[Dict[str, object]] = None + """A user profile object merged with user profile on send.""" diff --git a/src/courier/types/tenant_association.py b/src/courier/types/tenant_association.py new file mode 100644 index 00000000..71b84cb5 --- /dev/null +++ b/src/courier/types/tenant_association.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["TenantAssociation"] + + +class TenantAssociation(BaseModel): + tenant_id: str + """Tenant ID for the association between tenant and user""" + + profile: Optional[Dict[str, object]] = None + """ + Additional metadata to be applied to a user profile when used in a tenant + context + """ + + type: Optional[Literal["user"]] = None + + user_id: Optional[str] = None + """User ID for the association between tenant and user""" diff --git a/src/courier/types/tenant_association_param.py b/src/courier/types/tenant_association_param.py new file mode 100644 index 00000000..6306f096 --- /dev/null +++ b/src/courier/types/tenant_association_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["TenantAssociationParam"] + + +class TenantAssociationParam(TypedDict, total=False): + tenant_id: Required[str] + """Tenant ID for the association between tenant and user""" + + profile: Optional[Dict[str, object]] + """ + Additional metadata to be applied to a user profile when used in a tenant + context + """ + + type: Optional[Literal["user"]] + + user_id: Optional[str] + """User ID for the association between tenant and user""" diff --git a/src/courier/types/tenant_list_params.py b/src/courier/types/tenant_list_params.py new file mode 100644 index 00000000..8d78807d --- /dev/null +++ b/src/courier/types/tenant_list_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["TenantListParams"] + + +class TenantListParams(TypedDict, total=False): + cursor: Optional[str] + """Continue the pagination with the next cursor""" + + limit: Optional[int] + """The number of tenants to return (defaults to 20, maximum value of 100)""" + + parent_tenant_id: Optional[str] + """Filter the list of tenants by parent_id""" diff --git a/src/courier/types/tenant_list_response.py b/src/courier/types/tenant_list_response.py new file mode 100644 index 00000000..cc2e3a1b --- /dev/null +++ b/src/courier/types/tenant_list_response.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .tenant import Tenant +from .._models import BaseModel + +__all__ = ["TenantListResponse"] + + +class TenantListResponse(BaseModel): + has_more: bool + """Set to true when there are more pages that can be retrieved.""" + + items: List[Tenant] + """An array of Tenants""" + + type: Literal["list"] + """Always set to "list". Represents the type of this object.""" + + url: str + """A url that may be used to generate these results.""" + + cursor: Optional[str] = None + """A pointer to the next page of results. + + Defined only when has_more is set to true. + """ + + next_url: Optional[str] = None + """A url that may be used to generate fetch the next set of results. + + Defined only when has_more is set to true + """ diff --git a/src/courier/types/tenant_list_users_params.py b/src/courier/types/tenant_list_users_params.py new file mode 100644 index 00000000..840210f4 --- /dev/null +++ b/src/courier/types/tenant_list_users_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["TenantListUsersParams"] + + +class TenantListUsersParams(TypedDict, total=False): + cursor: Optional[str] + """Continue the pagination with the next cursor""" + + limit: Optional[int] + """The number of accounts to return (defaults to 20, maximum value of 100)""" diff --git a/src/courier/types/tenant_list_users_response.py b/src/courier/types/tenant_list_users_response.py new file mode 100644 index 00000000..5b4f9c20 --- /dev/null +++ b/src/courier/types/tenant_list_users_response.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .tenant_association import TenantAssociation + +__all__ = ["TenantListUsersResponse"] + + +class TenantListUsersResponse(BaseModel): + has_more: bool + """Set to true when there are more pages that can be retrieved.""" + + type: Literal["list"] + """Always set to `list`. Represents the type of this object.""" + + url: str + """A url that may be used to generate these results.""" + + cursor: Optional[str] = None + """A pointer to the next page of results. + + Defined only when `has_more` is set to true + """ + + items: Optional[List[TenantAssociation]] = None + + next_url: Optional[str] = None + """A url that may be used to generate fetch the next set of results. + + Defined only when `has_more` is set to true + """ diff --git a/src/courier/types/tenant_template_input_param.py b/src/courier/types/tenant_template_input_param.py new file mode 100644 index 00000000..9b208d93 --- /dev/null +++ b/src/courier/types/tenant_template_input_param.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .shared_params.message_channels import MessageChannels +from .shared_params.elemental_content import ElementalContent +from .shared_params.message_providers import MessageProviders + +__all__ = ["TenantTemplateInputParam"] + + +class TenantTemplateInputParam(TypedDict, total=False): + """Template configuration for creating or updating a tenant notification template""" + + content: Required[ElementalContent] + """ + Template content configuration including blocks, elements, and message structure + """ + + channels: MessageChannels + """Channel-specific delivery configuration (email, SMS, push, etc.)""" + + providers: MessageProviders + """ + Provider-specific delivery configuration for routing to specific email/SMS + providers + """ + + routing: "MessageRouting" + """Message routing configuration for multi-channel delivery strategies""" + + +from .shared_params.message_routing import MessageRouting diff --git a/src/courier/types/tenant_update_params.py b/src/courier/types/tenant_update_params.py new file mode 100644 index 00000000..9b896a18 --- /dev/null +++ b/src/courier/types/tenant_update_params.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Required, TypedDict + +from .default_preferences_param import DefaultPreferencesParam + +__all__ = ["TenantUpdateParams"] + + +class TenantUpdateParams(TypedDict, total=False): + name: Required[str] + """Name of the tenant.""" + + brand_id: Optional[str] + """Brand to be used for the account when one is not specified by the send call.""" + + default_preferences: Optional[DefaultPreferencesParam] + """ + Defines the preferences used for the tenant when the user hasn't specified their + own. + """ + + parent_tenant_id: Optional[str] + """Tenant's parent id (if any).""" + + properties: Optional[Dict[str, object]] + """Arbitrary properties accessible to a template.""" + + user_profile: Optional[Dict[str, object]] + """A user profile object merged with user profile on send.""" diff --git a/src/courier/types/tenants/__init__.py b/src/courier/types/tenants/__init__.py new file mode 100644 index 00000000..bd059884 --- /dev/null +++ b/src/courier/types/tenants/__init__.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .template_list_params import TemplateListParams as TemplateListParams +from .template_list_response import TemplateListResponse as TemplateListResponse +from .template_publish_params import TemplatePublishParams as TemplatePublishParams +from .template_replace_params import TemplateReplaceParams as TemplateReplaceParams diff --git a/src/courier/types/tenants/preferences/__init__.py b/src/courier/types/tenants/preferences/__init__.py new file mode 100644 index 00000000..8a110bf2 --- /dev/null +++ b/src/courier/types/tenants/preferences/__init__.py @@ -0,0 +1,5 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .item_update_params import ItemUpdateParams as ItemUpdateParams diff --git a/src/courier/types/tenants/preferences/item_update_params.py b/src/courier/types/tenants/preferences/item_update_params.py new file mode 100644 index 00000000..78970e31 --- /dev/null +++ b/src/courier/types/tenants/preferences/item_update_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ...shared.channel_classification import ChannelClassification + +__all__ = ["ItemUpdateParams"] + + +class ItemUpdateParams(TypedDict, total=False): + tenant_id: Required[str] + + status: Required[Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"]] + + custom_routing: Optional[List[ChannelClassification]] + """The default channels to send to this tenant when has_custom_routing is enabled""" + + has_custom_routing: Optional[bool] + """Override channel routing with custom preferences. + + This will override any template preferences that are set, but a user can still + customize their preferences + """ diff --git a/src/courier/types/tenants/template_list_params.py b/src/courier/types/tenants/template_list_params.py new file mode 100644 index 00000000..0d69d7de --- /dev/null +++ b/src/courier/types/tenants/template_list_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["TemplateListParams"] + + +class TemplateListParams(TypedDict, total=False): + cursor: Optional[str] + """Continue the pagination with the next cursor""" + + limit: Optional[int] + """The number of templates to return (defaults to 20, maximum value of 100)""" diff --git a/src/courier/types/tenants/template_list_response.py b/src/courier/types/tenants/template_list_response.py new file mode 100644 index 00000000..d7e05a83 --- /dev/null +++ b/src/courier/types/tenants/template_list_response.py @@ -0,0 +1,50 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from ..base_template_tenant_association import BaseTemplateTenantAssociation + +__all__ = ["TemplateListResponse", "Item", "ItemData"] + + +class ItemData(BaseModel): + """The template's data containing it's routing configs""" + + routing: "MessageRouting" + + +class Item(BaseTemplateTenantAssociation): + data: ItemData + """The template's data containing it's routing configs""" + + +class TemplateListResponse(BaseModel): + has_more: bool + """Set to true when there are more pages that can be retrieved.""" + + type: Literal["list"] + """Always set to `list`. Represents the type of this object.""" + + url: str + """A url that may be used to generate these results.""" + + cursor: Optional[str] = None + """A pointer to the next page of results. + + Defined only when `has_more` is set to true + """ + + items: Optional[List[Item]] = None + + next_url: Optional[str] = None + """A url that may be used to generate fetch the next set of results. + + Defined only when `has_more` is set to true + """ + + +from ..shared.message_routing import MessageRouting diff --git a/src/courier/types/tenants/template_publish_params.py b/src/courier/types/tenants/template_publish_params.py new file mode 100644 index 00000000..75f35708 --- /dev/null +++ b/src/courier/types/tenants/template_publish_params.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["TemplatePublishParams"] + + +class TemplatePublishParams(TypedDict, total=False): + tenant_id: Required[str] + + version: str + """The version of the template to publish (e.g., "v1", "v2", "latest"). + + If not provided, defaults to "latest". + """ diff --git a/src/courier/types/tenants/template_replace_params.py b/src/courier/types/tenants/template_replace_params.py new file mode 100644 index 00000000..69a92b1f --- /dev/null +++ b/src/courier/types/tenants/template_replace_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["TemplateReplaceParams"] + + +class TemplateReplaceParams(TypedDict, total=False): + tenant_id: Required[str] + + template: Required["TenantTemplateInputParam"] + """Template configuration for creating or updating a tenant notification template""" + + published: bool + """Whether to publish the template immediately after saving. + + When true, the template becomes the active/published version. When false + (default), the template is saved as a draft. + """ + + +from ..tenant_template_input_param import TenantTemplateInputParam diff --git a/src/courier/types/tenants/templates/__init__.py b/src/courier/types/tenants/templates/__init__.py new file mode 100644 index 00000000..f8ee8b14 --- /dev/null +++ b/src/courier/types/tenants/templates/__init__.py @@ -0,0 +1,3 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations diff --git a/src/courier/types/translation_retrieve_response.py b/src/courier/types/translation_retrieve_response.py new file mode 100644 index 00000000..c5a1ddea --- /dev/null +++ b/src/courier/types/translation_retrieve_response.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import TypeAlias + +__all__ = ["TranslationRetrieveResponse"] + +TranslationRetrieveResponse: TypeAlias = str diff --git a/src/courier/types/translation_update_params.py b/src/courier/types/translation_update_params.py new file mode 100644 index 00000000..ae23fa3d --- /dev/null +++ b/src/courier/types/translation_update_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["TranslationUpdateParams"] + + +class TranslationUpdateParams(TypedDict, total=False): + domain: Required[str] + + body: Required[str] diff --git a/src/courier/types/users/__init__.py b/src/courier/types/users/__init__.py new file mode 100644 index 00000000..94bf6ed2 --- /dev/null +++ b/src/courier/types/users/__init__.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .user_token import UserToken as UserToken +from .topic_preference import TopicPreference as TopicPreference +from .tenant_list_params import TenantListParams as TenantListParams +from .token_list_response import TokenListResponse as TokenListResponse +from .token_update_params import TokenUpdateParams as TokenUpdateParams +from .tenant_list_response import TenantListResponse as TenantListResponse +from .bulk_preference_topic import BulkPreferenceTopic as BulkPreferenceTopic +from .token_add_single_params import TokenAddSingleParams as TokenAddSingleParams +from .token_retrieve_response import TokenRetrieveResponse as TokenRetrieveResponse +from .tenant_add_single_params import TenantAddSingleParams as TenantAddSingleParams +from .preference_retrieve_params import PreferenceRetrieveParams as PreferenceRetrieveParams +from .tenant_add_multiple_params import TenantAddMultipleParams as TenantAddMultipleParams +from .preference_retrieve_response import PreferenceRetrieveResponse as PreferenceRetrieveResponse +from .preference_bulk_update_params import PreferenceBulkUpdateParams as PreferenceBulkUpdateParams +from .preference_bulk_replace_params import PreferenceBulkReplaceParams as PreferenceBulkReplaceParams +from .preference_delete_topic_params import PreferenceDeleteTopicParams as PreferenceDeleteTopicParams +from .preference_bulk_update_response import PreferenceBulkUpdateResponse as PreferenceBulkUpdateResponse +from .preference_bulk_replace_response import PreferenceBulkReplaceResponse as PreferenceBulkReplaceResponse +from .preference_retrieve_topic_params import PreferenceRetrieveTopicParams as PreferenceRetrieveTopicParams +from .preference_retrieve_topic_response import PreferenceRetrieveTopicResponse as PreferenceRetrieveTopicResponse +from .preference_update_or_create_topic_params import ( + PreferenceUpdateOrCreateTopicParams as PreferenceUpdateOrCreateTopicParams, +) +from .preference_update_or_create_topic_response import ( + PreferenceUpdateOrCreateTopicResponse as PreferenceUpdateOrCreateTopicResponse, +) diff --git a/src/courier/types/users/bulk_preference_topic.py b/src/courier/types/users/bulk_preference_topic.py new file mode 100644 index 00000000..b36d109c --- /dev/null +++ b/src/courier/types/users/bulk_preference_topic.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import Literal + +from ..._models import BaseModel +from ..shared.channel_classification import ChannelClassification + +__all__ = ["BulkPreferenceTopic"] + + +class BulkPreferenceTopic(BaseModel): + """A single topic override echoed in a bulk preference response.""" + + custom_routing: List[ChannelClassification] + + has_custom_routing: bool + + status: Literal["OPTED_IN", "OPTED_OUT"] + """The applied subscription status. + + Echoes the requested value, so it is always OPTED_IN or OPTED_OUT. + """ + + topic_id: str diff --git a/src/courier/types/users/preference_bulk_replace_params.py b/src/courier/types/users/preference_bulk_replace_params.py new file mode 100644 index 00000000..ff7c8598 --- /dev/null +++ b/src/courier/types/users/preference_bulk_replace_params.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..shared.channel_classification import ChannelClassification + +__all__ = ["PreferenceBulkReplaceParams", "Topic"] + + +class PreferenceBulkReplaceParams(TypedDict, total=False): + topics: Required[Iterable[Topic]] + """The complete set of topic overrides for the user. + + Up to 50 topics may be provided. Any existing override not listed here is reset + to its topic default; an empty array resets every existing override. + """ + + tenant_id: Optional[str] + """Replace the preferences of a user for this specific tenant context.""" + + +class Topic(TypedDict, total=False): + status: Required[Literal["OPTED_IN", "OPTED_OUT"]] + """The subscription status to apply for this topic.""" + + topic_id: Required[str] + """A unique identifier associated with a subscription topic.""" + + custom_routing: List[ChannelClassification] + """The channels a user has chosen to receive notifications through for this topic.""" + + has_custom_routing: bool + """Whether the recipient has chosen specific delivery channels for this topic.""" diff --git a/src/courier/types/users/preference_bulk_replace_response.py b/src/courier/types/users/preference_bulk_replace_response.py new file mode 100644 index 00000000..2b3c2948 --- /dev/null +++ b/src/courier/types/users/preference_bulk_replace_response.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from .bulk_preference_topic import BulkPreferenceTopic + +__all__ = ["PreferenceBulkReplaceResponse"] + + +class PreferenceBulkReplaceResponse(BaseModel): + deleted: List[str] + """The ids of the overrides that were reset to their topic default.""" + + items: List[BulkPreferenceTopic] + """The complete resulting set of topic overrides for the user.""" diff --git a/src/courier/types/users/preference_bulk_update_params.py b/src/courier/types/users/preference_bulk_update_params.py new file mode 100644 index 00000000..0de00849 --- /dev/null +++ b/src/courier/types/users/preference_bulk_update_params.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Iterable, Optional +from typing_extensions import Literal, Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..shared.channel_classification import ChannelClassification + +__all__ = ["PreferenceBulkUpdateParams", "Topic"] + + +class PreferenceBulkUpdateParams(TypedDict, total=False): + topics: Required[Iterable[Topic]] + """The topics to create or update. + + Between 1 and 50 topics may be provided in a single request. + """ + + tenant_id: Optional[str] + """Update the preferences of a user for this specific tenant context.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] + + +class Topic(TypedDict, total=False): + status: Required[Literal["OPTED_IN", "OPTED_OUT"]] + """The subscription status to apply for this topic.""" + + topic_id: Required[str] + """A unique identifier associated with a subscription topic.""" + + custom_routing: List[ChannelClassification] + """The channels a user has chosen to receive notifications through for this topic.""" + + has_custom_routing: bool + """Whether the recipient has chosen specific delivery channels for this topic.""" diff --git a/src/courier/types/users/preference_bulk_update_response.py b/src/courier/types/users/preference_bulk_update_response.py new file mode 100644 index 00000000..d5eaa395 --- /dev/null +++ b/src/courier/types/users/preference_bulk_update_response.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from .bulk_preference_topic import BulkPreferenceTopic + +__all__ = ["PreferenceBulkUpdateResponse", "Error"] + + +class Error(BaseModel): + """A single topic that could not be applied in a bulk preference request.""" + + reason: str + """A human-readable explanation of why the topic could not be applied.""" + + topic_id: str + + +class PreferenceBulkUpdateResponse(BaseModel): + errors: List[Error] + """The topics that could not be applied, each with a reason.""" + + items: List[BulkPreferenceTopic] + """The topics that were successfully created or updated.""" diff --git a/src/courier/types/users/preference_delete_topic_params.py b/src/courier/types/users/preference_delete_topic_params.py new file mode 100644 index 00000000..517af311 --- /dev/null +++ b/src/courier/types/users/preference_delete_topic_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +__all__ = ["PreferenceDeleteTopicParams"] + + +class PreferenceDeleteTopicParams(TypedDict, total=False): + user_id: Required[str] + + tenant_id: Optional[str] + """Delete the preferences of a user for this specific tenant context.""" diff --git a/src/courier/types/users/preference_retrieve_params.py b/src/courier/types/users/preference_retrieve_params.py new file mode 100644 index 00000000..b4cb5841 --- /dev/null +++ b/src/courier/types/users/preference_retrieve_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["PreferenceRetrieveParams"] + + +class PreferenceRetrieveParams(TypedDict, total=False): + tenant_id: Optional[str] + """Query the preferences of a user for this specific tenant context.""" diff --git a/src/courier/types/users/preference_retrieve_response.py b/src/courier/types/users/preference_retrieve_response.py new file mode 100644 index 00000000..77a5432b --- /dev/null +++ b/src/courier/types/users/preference_retrieve_response.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from ..shared.paging import Paging +from .topic_preference import TopicPreference + +__all__ = ["PreferenceRetrieveResponse"] + + +class PreferenceRetrieveResponse(BaseModel): + items: List[TopicPreference] + """The Preferences associated with the user_id.""" + + paging: Paging + """Deprecated - Paging not implemented on this endpoint""" diff --git a/src/courier/types/users/preference_retrieve_topic_params.py b/src/courier/types/users/preference_retrieve_topic_params.py new file mode 100644 index 00000000..12554e1d --- /dev/null +++ b/src/courier/types/users/preference_retrieve_topic_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +__all__ = ["PreferenceRetrieveTopicParams"] + + +class PreferenceRetrieveTopicParams(TypedDict, total=False): + user_id: Required[str] + + tenant_id: Optional[str] + """Query the preferences of a user for this specific tenant context.""" diff --git a/src/courier/types/users/preference_retrieve_topic_response.py b/src/courier/types/users/preference_retrieve_topic_response.py new file mode 100644 index 00000000..7527e28d --- /dev/null +++ b/src/courier/types/users/preference_retrieve_topic_response.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel +from .topic_preference import TopicPreference + +__all__ = ["PreferenceRetrieveTopicResponse"] + + +class PreferenceRetrieveTopicResponse(BaseModel): + topic: TopicPreference diff --git a/src/courier/types/users/preference_update_or_create_topic_params.py b/src/courier/types/users/preference_update_or_create_topic_params.py new file mode 100644 index 00000000..6eb74fdd --- /dev/null +++ b/src/courier/types/users/preference_update_or_create_topic_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Required, TypedDict + +from ..shared.preference_status import PreferenceStatus +from ..shared.channel_classification import ChannelClassification + +__all__ = ["PreferenceUpdateOrCreateTopicParams", "Topic"] + + +class PreferenceUpdateOrCreateTopicParams(TypedDict, total=False): + user_id: Required[str] + + topic: Required[Topic] + + tenant_id: Optional[str] + """Update the preferences of a user for this specific tenant context.""" + + +class Topic(TypedDict, total=False): + status: Required[PreferenceStatus] + """The subscription status to set: OPTED_IN or OPTED_OUT. + + REQUIRED is a topic-level default, not a user choice; the API rejects opting a + user out of a REQUIRED topic. + """ + + custom_routing: Optional[List[ChannelClassification]] + """The channels to deliver this topic on when has_custom_routing is true. + + One or more of: direct_message, email, push, sms, webhook, inbox. + """ + + has_custom_routing: Optional[bool] + """ + Set to true to route this topic to the channels in custom_routing instead of the + topic's default routing. + """ diff --git a/src/courier/types/users/preference_update_or_create_topic_response.py b/src/courier/types/users/preference_update_or_create_topic_response.py new file mode 100644 index 00000000..93c24005 --- /dev/null +++ b/src/courier/types/users/preference_update_or_create_topic_response.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["PreferenceUpdateOrCreateTopicResponse"] + + +class PreferenceUpdateOrCreateTopicResponse(BaseModel): + message: str diff --git a/src/courier/types/users/tenant_add_multiple_params.py b/src/courier/types/users/tenant_add_multiple_params.py new file mode 100644 index 00000000..b0ef7ae8 --- /dev/null +++ b/src/courier/types/users/tenant_add_multiple_params.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Required, TypedDict + +from ..tenant_association_param import TenantAssociationParam + +__all__ = ["TenantAddMultipleParams"] + + +class TenantAddMultipleParams(TypedDict, total=False): + tenants: Required[Iterable[TenantAssociationParam]] diff --git a/src/courier/types/users/tenant_add_single_params.py b/src/courier/types/users/tenant_add_single_params.py new file mode 100644 index 00000000..3ee41f1e --- /dev/null +++ b/src/courier/types/users/tenant_add_single_params.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Required, TypedDict + +__all__ = ["TenantAddSingleParams"] + + +class TenantAddSingleParams(TypedDict, total=False): + user_id: Required[str] + + profile: Optional[Dict[str, object]] diff --git a/src/courier/types/users/tenant_list_params.py b/src/courier/types/users/tenant_list_params.py new file mode 100644 index 00000000..e40b62b6 --- /dev/null +++ b/src/courier/types/users/tenant_list_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["TenantListParams"] + + +class TenantListParams(TypedDict, total=False): + cursor: Optional[str] + """Continue the pagination with the next cursor""" + + limit: Optional[int] + """The number of accounts to return (defaults to 20, maximum value of 100)""" diff --git a/src/courier/types/users/tenant_list_response.py b/src/courier/types/users/tenant_list_response.py new file mode 100644 index 00000000..1115bf6d --- /dev/null +++ b/src/courier/types/users/tenant_list_response.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from ..tenant_association import TenantAssociation + +__all__ = ["TenantListResponse"] + + +class TenantListResponse(BaseModel): + has_more: bool + """Set to true when there are more pages that can be retrieved.""" + + type: Literal["list"] + """Always set to `list`. Represents the type of this object.""" + + url: str + """A url that may be used to generate these results.""" + + cursor: Optional[str] = None + """A pointer to the next page of results. + + Defined only when `has_more` is set to true + """ + + items: Optional[List[TenantAssociation]] = None + + next_url: Optional[str] = None + """A url that may be used to generate fetch the next set of results. + + Defined only when `has_more` is set to true + """ diff --git a/src/courier/types/users/token_add_single_params.py b/src/courier/types/users/token_add_single_params.py new file mode 100644 index 00000000..151ea841 --- /dev/null +++ b/src/courier/types/users/token_add_single_params.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["TokenAddSingleParams", "Device", "Tracking"] + + +class TokenAddSingleParams(TypedDict, total=False): + user_id: Required[str] + + provider_key: Required[Literal["firebase-fcm", "apn", "expo", "onesignal"]] + + device: Optional[Device] + """Information about the device the token came from.""" + + expiry_date: Union[str, bool, None] + """ISO 8601 formatted date the token expires. + + Defaults to 2 months. Set to false to disable expiration. + """ + + properties: object + """Properties about the token.""" + + tracking: Optional[Tracking] + """Tracking information about the device the token came from.""" + + +class Device(TypedDict, total=False): + """Information about the device the token came from.""" + + ad_id: Optional[str] + """Id of the advertising identifier""" + + app_id: Optional[str] + """Id of the application the token is used for""" + + device_id: Optional[str] + """Id of the device the token is associated with""" + + manufacturer: Optional[str] + """The device manufacturer""" + + model: Optional[str] + """The device model""" + + platform: Optional[str] + """The device platform i.e. android, ios, web""" + + +class Tracking(TypedDict, total=False): + """Tracking information about the device the token came from.""" + + ip: Optional[str] + """The IP address of the device""" + + lat: Optional[str] + """The latitude of the device""" + + long: Optional[str] + """The longitude of the device""" + + os_version: Optional[str] + """The operating system version""" diff --git a/src/courier/types/users/token_list_response.py b/src/courier/types/users/token_list_response.py new file mode 100644 index 00000000..3a8dd0c7 --- /dev/null +++ b/src/courier/types/users/token_list_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel +from .user_token import UserToken + +__all__ = ["TokenListResponse"] + + +class TokenListResponse(BaseModel): + """A list of tokens registered with the user.""" + + tokens: List[UserToken] diff --git a/src/courier/types/users/token_retrieve_response.py b/src/courier/types/users/token_retrieve_response.py new file mode 100644 index 00000000..ce803f2d --- /dev/null +++ b/src/courier/types/users/token_retrieve_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .user_token import UserToken + +__all__ = ["TokenRetrieveResponse"] + + +class TokenRetrieveResponse(UserToken): + status: Optional[Literal["active", "unknown", "failed", "revoked"]] = None + + status_reason: Optional[str] = None + """The reason for the token status.""" diff --git a/src/courier/types/users/token_update_params.py b/src/courier/types/users/token_update_params.py new file mode 100644 index 00000000..535c5e4d --- /dev/null +++ b/src/courier/types/users/token_update_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Required, TypedDict + +__all__ = ["TokenUpdateParams", "Patch"] + + +class TokenUpdateParams(TypedDict, total=False): + user_id: Required[str] + + patch: Required[Iterable[Patch]] + + +class Patch(TypedDict, total=False): + op: Required[str] + """The operation to perform.""" + + path: Required[str] + """The JSON path specifying the part of the profile to operate on.""" + + value: Optional[str] + """The value for the operation.""" diff --git a/src/courier/types/users/topic_preference.py b/src/courier/types/users/topic_preference.py new file mode 100644 index 00000000..b719e0e8 --- /dev/null +++ b/src/courier/types/users/topic_preference.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from ..._models import BaseModel +from ..shared.preference_status import PreferenceStatus +from ..shared.channel_classification import ChannelClassification + +__all__ = ["TopicPreference"] + + +class TopicPreference(BaseModel): + default_status: PreferenceStatus + """The topic's default status, returned on reads. + + It applies whenever the user has no override of their own (status equals this + value). + """ + + status: PreferenceStatus + """The user's subscription status for this topic. + + OPTED_IN or OPTED_OUT reflect the user's own choice; REQUIRED is a topic-level + default set in the preferences editor, not a user choice. + """ + + topic_id: str + """The unique identifier of the subscription topic this preference applies to.""" + + topic_name: str + """The display name of the subscription topic, returned on reads.""" + + custom_routing: Optional[List[ChannelClassification]] = None + """ + The channels the user has chosen to receive this topic on, present only when + has_custom_routing is true. One or more of: direct_message, email, push, sms, + webhook, inbox. + """ + + has_custom_routing: Optional[bool] = None + """ + Whether the user has chosen specific delivery channels for this topic (listed in + custom_routing) rather than the topic's default routing. + """ diff --git a/src/courier/types/users/user_token.py b/src/courier/types/users/user_token.py new file mode 100644 index 00000000..bff090f1 --- /dev/null +++ b/src/courier/types/users/user_token.py @@ -0,0 +1,68 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["UserToken", "Device", "Tracking"] + + +class Device(BaseModel): + """Information about the device the token came from.""" + + ad_id: Optional[str] = None + """Id of the advertising identifier""" + + app_id: Optional[str] = None + """Id of the application the token is used for""" + + device_id: Optional[str] = None + """Id of the device the token is associated with""" + + manufacturer: Optional[str] = None + """The device manufacturer""" + + model: Optional[str] = None + """The device model""" + + platform: Optional[str] = None + """The device platform i.e. android, ios, web""" + + +class Tracking(BaseModel): + """Tracking information about the device the token came from.""" + + ip: Optional[str] = None + """The IP address of the device""" + + lat: Optional[str] = None + """The latitude of the device""" + + long: Optional[str] = None + """The longitude of the device""" + + os_version: Optional[str] = None + """The operating system version""" + + +class UserToken(BaseModel): + token: str + """Full body of the token. Must match token in URL path parameter.""" + + provider_key: Literal["firebase-fcm", "apn", "expo", "onesignal"] + + device: Optional[Device] = None + """Information about the device the token came from.""" + + expiry_date: Union[str, bool, None] = None + """ISO 8601 formatted date the token expires. + + Defaults to 2 months. Set to false to disable expiration. + """ + + properties: Optional[object] = None + """Properties about the token.""" + + tracking: Optional[Tracking] = None + """Tracking information about the device the token came from.""" diff --git a/src/courier/types/version_node.py b/src/courier/types/version_node.py new file mode 100644 index 00000000..cfee173b --- /dev/null +++ b/src/courier/types/version_node.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["VersionNode"] + + +class VersionNode(BaseModel): + """A version entry for a notification template.""" + + created: int + """Epoch milliseconds when this version was created.""" + + creator: str + """User ID of the version creator.""" + + version: str + """Version identifier. + + One of "draft", "published:vNNN" (current published version), or "vNNN" + (historical version). + """ + + has_changes: Optional[bool] = None + """Whether the draft has unpublished changes. Only present on the draft version.""" diff --git a/src/courier/types/widget_background.py b/src/courier/types/widget_background.py new file mode 100644 index 00000000..b8a421a9 --- /dev/null +++ b/src/courier/types/widget_background.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["WidgetBackground"] + + +class WidgetBackground(BaseModel): + bottom_color: Optional[str] = FieldInfo(alias="bottomColor", default=None) + + top_color: Optional[str] = FieldInfo(alias="topColor", default=None) diff --git a/src/courier/types/widget_background_param.py b/src/courier/types/widget_background_param.py new file mode 100644 index 00000000..0293299b --- /dev/null +++ b/src/courier/types/widget_background_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["WidgetBackgroundParam"] + + +class WidgetBackgroundParam(TypedDict, total=False): + bottom_color: Annotated[Optional[str], PropertyInfo(alias="bottomColor")] + + top_color: Annotated[Optional[str], PropertyInfo(alias="topColor")] diff --git a/src/courier/types/workspace_preference_create_params.py b/src/courier/types/workspace_preference_create_params.py new file mode 100644 index 00000000..c5dbbf10 --- /dev/null +++ b/src/courier/types/workspace_preference_create_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Required, Annotated, TypedDict + +from .._utils import PropertyInfo +from .shared.channel_classification import ChannelClassification + +__all__ = ["WorkspacePreferenceCreateParams"] + + +class WorkspacePreferenceCreateParams(TypedDict, total=False): + name: Required[str] + """Human-readable name for the workspace preference.""" + + description: Optional[str] + """Optional description shown under the section on the hosted preferences page.""" + + has_custom_routing: Optional[bool] + """Whether the workspace preference defines custom routing for its topics.""" + + routing_options: Optional[List[ChannelClassification]] + """Default channels for the workspace preference. Defaults to empty if omitted.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/workspace_preference_get_response.py b/src/courier/types/workspace_preference_get_response.py new file mode 100644 index 00000000..d9d0de7d --- /dev/null +++ b/src/courier/types/workspace_preference_get_response.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel +from .shared.channel_classification import ChannelClassification +from .workspace_preference_topic_get_response import WorkspacePreferenceTopicGetResponse + +__all__ = ["WorkspacePreferenceGetResponse"] + + +class WorkspacePreferenceGetResponse(BaseModel): + """A workspace preference in your workspace, including its topics.""" + + id: str + """The workspace preference id.""" + + created: str + """ISO-8601 timestamp of when the workspace preference was created.""" + + has_custom_routing: bool + """Whether the workspace preference defines custom routing for its topics.""" + + name: str + """Human-readable name.""" + + routing_options: List[ChannelClassification] + """Default channels for the workspace preference. May be empty.""" + + topics: List[WorkspacePreferenceTopicGetResponse] + """The topics contained in this workspace preference.""" + + creator: Optional[str] = None + """Id of the creator.""" + + description: Optional[str] = None + """Optional description shown under the section on the hosted preferences page.""" + + updated: Optional[str] = None + """ISO-8601 timestamp of the last update.""" + + updater: Optional[str] = None + """Id of the last updater.""" diff --git a/src/courier/types/workspace_preference_list_response.py b/src/courier/types/workspace_preference_list_response.py new file mode 100644 index 00000000..4dfe47f9 --- /dev/null +++ b/src/courier/types/workspace_preference_list_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .workspace_preference_get_response import WorkspacePreferenceGetResponse + +__all__ = ["WorkspacePreferenceListResponse"] + + +class WorkspacePreferenceListResponse(BaseModel): + """The workspace's preferences, each with its topics.""" + + results: List[WorkspacePreferenceGetResponse] diff --git a/src/courier/types/workspace_preference_publish_params.py b/src/courier/types/workspace_preference_publish_params.py new file mode 100644 index 00000000..50e3b0fb --- /dev/null +++ b/src/courier/types/workspace_preference_publish_params.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Annotated, TypedDict + +from .._utils import PropertyInfo + +__all__ = ["WorkspacePreferencePublishParams"] + + +class WorkspacePreferencePublishParams(TypedDict, total=False): + brand_id: Optional[str] + """ + Brand for the hosted page - "default" (workspace default brand), "none" (no + brand), or a specific brand id. Defaults to "default". + """ + + description: Optional[str] + """Description shown under the heading on the hosted preferences page.""" + + heading: Optional[str] + """Heading shown at the top of the hosted preferences page.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/workspace_preference_replace_params.py b/src/courier/types/workspace_preference_replace_params.py new file mode 100644 index 00000000..79f60920 --- /dev/null +++ b/src/courier/types/workspace_preference_replace_params.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Required, TypedDict + +from .shared.channel_classification import ChannelClassification + +__all__ = ["WorkspacePreferenceReplaceParams"] + + +class WorkspacePreferenceReplaceParams(TypedDict, total=False): + name: Required[str] + """Human-readable name for the workspace preference.""" + + description: Optional[str] + """Optional description shown under the section on the hosted preferences page. + + Omit to clear. + """ + + has_custom_routing: Optional[bool] + """Whether the workspace preference defines custom routing for its topics.""" + + routing_options: Optional[List[ChannelClassification]] + """Default channels for the workspace preference. Omit to clear.""" diff --git a/src/courier/types/workspace_preference_topic_get_response.py b/src/courier/types/workspace_preference_topic_get_response.py new file mode 100644 index 00000000..bf10ef4d --- /dev/null +++ b/src/courier/types/workspace_preference_topic_get_response.py @@ -0,0 +1,49 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .shared.channel_classification import ChannelClassification + +__all__ = ["WorkspacePreferenceTopicGetResponse"] + + +class WorkspacePreferenceTopicGetResponse(BaseModel): + """A subscription preference topic in your workspace.""" + + id: str + """The preference topic id.""" + + allowed_preferences: List[Literal["snooze", "channel_preferences"]] + """Preference controls a recipient may customize. May be empty.""" + + created: str + """ISO-8601 timestamp of when the topic was created.""" + + default_status: Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"] + """The default subscription status applied when a recipient has not set their own.""" + + include_unsubscribe_header: bool + """Whether a list-unsubscribe header is included on emails for this topic.""" + + name: str + """Human-readable name.""" + + routing_options: List[ChannelClassification] + """Default channels delivered for this topic. May be empty.""" + + topic_data: Dict[str, object] + """Arbitrary metadata associated with the topic.""" + + updated: str + """ISO-8601 timestamp of the last update.""" + + creator: Optional[str] = None + """Id of the creator.""" + + description: Optional[str] = None + """Optional description shown under the topic on the hosted preferences page.""" + + updater: Optional[str] = None + """Id of the last updater.""" diff --git a/src/courier/types/workspace_preference_topic_list_response.py b/src/courier/types/workspace_preference_topic_list_response.py new file mode 100644 index 00000000..afdb082c --- /dev/null +++ b/src/courier/types/workspace_preference_topic_list_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from .._models import BaseModel +from .workspace_preference_topic_get_response import WorkspacePreferenceTopicGetResponse + +__all__ = ["WorkspacePreferenceTopicListResponse"] + + +class WorkspacePreferenceTopicListResponse(BaseModel): + """Topics contained in a workspace preference.""" + + results: List[WorkspacePreferenceTopicGetResponse] diff --git a/src/courier/types/workspace_preferences/__init__.py b/src/courier/types/workspace_preferences/__init__.py new file mode 100644 index 00000000..43664cc4 --- /dev/null +++ b/src/courier/types/workspace_preferences/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .topic_create_params import TopicCreateParams as TopicCreateParams +from .topic_replace_params import TopicReplaceParams as TopicReplaceParams diff --git a/src/courier/types/workspace_preferences/topic_create_params.py b/src/courier/types/workspace_preferences/topic_create_params.py new file mode 100644 index 00000000..d6a926e3 --- /dev/null +++ b/src/courier/types/workspace_preferences/topic_create_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Literal, Required, Annotated, TypedDict + +from ..._utils import PropertyInfo +from ..shared.channel_classification import ChannelClassification + +__all__ = ["TopicCreateParams"] + + +class TopicCreateParams(TypedDict, total=False): + default_status: Required[Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"]] + """The default subscription status applied when a recipient has not set their own.""" + + name: Required[str] + """Human-readable name for the preference topic.""" + + allowed_preferences: Optional[List[Literal["snooze", "channel_preferences"]]] + """Preference controls a recipient may customize for this topic. + + Defaults to empty if omitted. + """ + + description: Optional[str] + """Optional description shown under the topic on the hosted preferences page.""" + + include_unsubscribe_header: Optional[bool] + """Whether to include a list-unsubscribe header on emails for this topic.""" + + routing_options: Optional[List[ChannelClassification]] + """Default channels delivered for this topic. Defaults to empty if omitted.""" + + topic_data: Optional[Dict[str, object]] + """Arbitrary metadata associated with the topic.""" + + idempotency_key: Annotated[str, PropertyInfo(alias="Idempotency-Key")] + + x_idempotency_expiration: Annotated[str, PropertyInfo(alias="x-idempotency-expiration")] diff --git a/src/courier/types/workspace_preferences/topic_replace_params.py b/src/courier/types/workspace_preferences/topic_replace_params.py new file mode 100644 index 00000000..7f2e3240 --- /dev/null +++ b/src/courier/types/workspace_preferences/topic_replace_params.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Optional +from typing_extensions import Literal, Required, TypedDict + +from ..shared.channel_classification import ChannelClassification + +__all__ = ["TopicReplaceParams"] + + +class TopicReplaceParams(TypedDict, total=False): + section_id: Required[str] + + default_status: Required[Literal["OPTED_OUT", "OPTED_IN", "REQUIRED"]] + """The default subscription status applied when a recipient has not set their own.""" + + name: Required[str] + """Human-readable name for the preference topic.""" + + allowed_preferences: Optional[List[Literal["snooze", "channel_preferences"]]] + """Preference controls a recipient may customize. Omit to clear.""" + + description: Optional[str] + """Optional description shown under the topic on the hosted preferences page. + + Omit to clear. + """ + + include_unsubscribe_header: Optional[bool] + """Whether to include a list-unsubscribe header on emails for this topic.""" + + routing_options: Optional[List[ChannelClassification]] + """Default channels delivered for this topic. Omit to clear.""" + + topic_data: Optional[Dict[str, object]] + """Arbitrary metadata associated with the topic. Omit to clear.""" diff --git a/src/courier_docs/lib/.keep b/src/courier_docs/lib/.keep new file mode 100644 index 00000000..5e2c99fd --- /dev/null +++ b/src/courier_docs/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/__init__.py b/tests/api_resources/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/automations/__init__.py b/tests/api_resources/automations/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/automations/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/automations/test_invoke.py b/tests/api_resources/automations/test_invoke.py new file mode 100644 index 00000000..a2fd132a --- /dev/null +++ b/tests/api_resources/automations/test_invoke.py @@ -0,0 +1,278 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import AutomationInvokeResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestInvoke: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_invoke_ad_hoc(self, client: Courier) -> None: + invoke = client.automations.invoke.invoke_ad_hoc( + automation={"steps": [{"action": "delay"}, {"action": "send"}]}, + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_invoke_ad_hoc_with_all_params(self, client: Courier) -> None: + invoke = client.automations.invoke.invoke_ad_hoc( + automation={ + "steps": [ + { + "action": "delay", + "duration": "duration", + "until": "20240408T080910.123", + }, + { + "action": "send", + "brand": "brand", + "data": {"foo": "bar"}, + "profile": {"foo": "bar"}, + "recipient": "recipient", + "template": "64TP5HKPFTM8VTK1Y75SJDQX9JK0", + }, + ], + "cancelation_token": "delay-send--user-yes--abc-123", + }, + brand="brand", + data={"name": "bar"}, + profile={"tenant_id": "bar"}, + recipient="user-yes", + template="template", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_invoke_ad_hoc(self, client: Courier) -> None: + response = client.automations.invoke.with_raw_response.invoke_ad_hoc( + automation={"steps": [{"action": "delay"}, {"action": "send"}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + invoke = response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_invoke_ad_hoc(self, client: Courier) -> None: + with client.automations.invoke.with_streaming_response.invoke_ad_hoc( + automation={"steps": [{"action": "delay"}, {"action": "send"}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + invoke = response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_invoke_by_template(self, client: Courier) -> None: + invoke = client.automations.invoke.invoke_by_template( + template_id="templateId", + recipient="recipient", + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_invoke_by_template_with_all_params(self, client: Courier) -> None: + invoke = client.automations.invoke.invoke_by_template( + template_id="templateId", + recipient="recipient", + brand="brand", + data={"foo": "bar"}, + profile={"foo": "bar"}, + template="template", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_invoke_by_template(self, client: Courier) -> None: + response = client.automations.invoke.with_raw_response.invoke_by_template( + template_id="templateId", + recipient="recipient", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + invoke = response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_invoke_by_template(self, client: Courier) -> None: + with client.automations.invoke.with_streaming_response.invoke_by_template( + template_id="templateId", + recipient="recipient", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + invoke = response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_invoke_by_template(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.automations.invoke.with_raw_response.invoke_by_template( + template_id="", + recipient="recipient", + ) + + +class TestAsyncInvoke: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_invoke_ad_hoc(self, async_client: AsyncCourier) -> None: + invoke = await async_client.automations.invoke.invoke_ad_hoc( + automation={"steps": [{"action": "delay"}, {"action": "send"}]}, + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_invoke_ad_hoc_with_all_params(self, async_client: AsyncCourier) -> None: + invoke = await async_client.automations.invoke.invoke_ad_hoc( + automation={ + "steps": [ + { + "action": "delay", + "duration": "duration", + "until": "20240408T080910.123", + }, + { + "action": "send", + "brand": "brand", + "data": {"foo": "bar"}, + "profile": {"foo": "bar"}, + "recipient": "recipient", + "template": "64TP5HKPFTM8VTK1Y75SJDQX9JK0", + }, + ], + "cancelation_token": "delay-send--user-yes--abc-123", + }, + brand="brand", + data={"name": "bar"}, + profile={"tenant_id": "bar"}, + recipient="user-yes", + template="template", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_invoke_ad_hoc(self, async_client: AsyncCourier) -> None: + response = await async_client.automations.invoke.with_raw_response.invoke_ad_hoc( + automation={"steps": [{"action": "delay"}, {"action": "send"}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + invoke = await response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_invoke_ad_hoc(self, async_client: AsyncCourier) -> None: + async with async_client.automations.invoke.with_streaming_response.invoke_ad_hoc( + automation={"steps": [{"action": "delay"}, {"action": "send"}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + invoke = await response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_invoke_by_template(self, async_client: AsyncCourier) -> None: + invoke = await async_client.automations.invoke.invoke_by_template( + template_id="templateId", + recipient="recipient", + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_invoke_by_template_with_all_params(self, async_client: AsyncCourier) -> None: + invoke = await async_client.automations.invoke.invoke_by_template( + template_id="templateId", + recipient="recipient", + brand="brand", + data={"foo": "bar"}, + profile={"foo": "bar"}, + template="template", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_invoke_by_template(self, async_client: AsyncCourier) -> None: + response = await async_client.automations.invoke.with_raw_response.invoke_by_template( + template_id="templateId", + recipient="recipient", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + invoke = await response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_invoke_by_template(self, async_client: AsyncCourier) -> None: + async with async_client.automations.invoke.with_streaming_response.invoke_by_template( + template_id="templateId", + recipient="recipient", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + invoke = await response.parse() + assert_matches_type(AutomationInvokeResponse, invoke, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_invoke_by_template(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.automations.invoke.with_raw_response.invoke_by_template( + template_id="", + recipient="recipient", + ) diff --git a/tests/api_resources/digests/__init__.py b/tests/api_resources/digests/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/digests/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/digests/test_schedules.py b/tests/api_resources/digests/test_schedules.py new file mode 100644 index 00000000..eac3666a --- /dev/null +++ b/tests/api_resources/digests/test_schedules.py @@ -0,0 +1,212 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import DigestInstanceListResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestSchedules: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_instances(self, client: Courier) -> None: + schedule = client.digests.schedules.list_instances( + schedule_id="schedule_id", + ) + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_instances_with_all_params(self, client: Courier) -> None: + schedule = client.digests.schedules.list_instances( + schedule_id="schedule_id", + cursor="cursor", + limit=100, + ) + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_instances(self, client: Courier) -> None: + response = client.digests.schedules.with_raw_response.list_instances( + schedule_id="schedule_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + schedule = response.parse() + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_instances(self, client: Courier) -> None: + with client.digests.schedules.with_streaming_response.list_instances( + schedule_id="schedule_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + schedule = response.parse() + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_instances(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schedule_id` but received ''"): + client.digests.schedules.with_raw_response.list_instances( + schedule_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_release(self, client: Courier) -> None: + schedule = client.digests.schedules.release( + "schedule_id", + ) + assert schedule is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_release(self, client: Courier) -> None: + response = client.digests.schedules.with_raw_response.release( + "schedule_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + schedule = response.parse() + assert schedule is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_release(self, client: Courier) -> None: + with client.digests.schedules.with_streaming_response.release( + "schedule_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + schedule = response.parse() + assert schedule is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_release(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schedule_id` but received ''"): + client.digests.schedules.with_raw_response.release( + "", + ) + + +class TestAsyncSchedules: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_instances(self, async_client: AsyncCourier) -> None: + schedule = await async_client.digests.schedules.list_instances( + schedule_id="schedule_id", + ) + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_instances_with_all_params(self, async_client: AsyncCourier) -> None: + schedule = await async_client.digests.schedules.list_instances( + schedule_id="schedule_id", + cursor="cursor", + limit=100, + ) + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_instances(self, async_client: AsyncCourier) -> None: + response = await async_client.digests.schedules.with_raw_response.list_instances( + schedule_id="schedule_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + schedule = await response.parse() + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_instances(self, async_client: AsyncCourier) -> None: + async with async_client.digests.schedules.with_streaming_response.list_instances( + schedule_id="schedule_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + schedule = await response.parse() + assert_matches_type(DigestInstanceListResponse, schedule, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_instances(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schedule_id` but received ''"): + await async_client.digests.schedules.with_raw_response.list_instances( + schedule_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_release(self, async_client: AsyncCourier) -> None: + schedule = await async_client.digests.schedules.release( + "schedule_id", + ) + assert schedule is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_release(self, async_client: AsyncCourier) -> None: + response = await async_client.digests.schedules.with_raw_response.release( + "schedule_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + schedule = await response.parse() + assert schedule is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_release(self, async_client: AsyncCourier) -> None: + async with async_client.digests.schedules.with_streaming_response.release( + "schedule_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + schedule = await response.parse() + assert schedule is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_release(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `schedule_id` but received ''"): + await async_client.digests.schedules.with_raw_response.release( + "", + ) diff --git a/tests/api_resources/journeys/__init__.py b/tests/api_resources/journeys/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/journeys/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/journeys/test_templates.py b/tests/api_resources/journeys/test_templates.py new file mode 100644 index 00000000..bde3602b --- /dev/null +++ b/tests/api_resources/journeys/test_templates.py @@ -0,0 +1,1502 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + JourneyTemplateGetResponse, + JourneyTemplateListResponse, + NotificationContentGetResponse, + NotificationContentMutationResponse, + NotificationTemplateVersionListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTemplates: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + template = client.journeys.templates.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + } + ], + "version": "2022-01-01", + "scope": "default", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + provider_key="x", + state="state", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_create(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.create( + template_id="", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + template = client.journeys.templates.retrieve( + notification_id="x", + template_id="x", + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.retrieve( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.retrieve( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.retrieve( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.retrieve( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + template = client.journeys.templates.list( + template_id="x", + ) + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.list( + template_id="x", + cursor="cursor", + limit=1, + ) + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.list( + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.list( + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.list( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + template = client.journeys.templates.archive( + notification_id="x", + template_id="x", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.archive( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.archive( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert template is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.archive( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.archive( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_versions(self, client: Courier) -> None: + template = client.journeys.templates.list_versions( + notification_id="x", + template_id="x", + ) + assert_matches_type(NotificationTemplateVersionListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_versions(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.list_versions( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_versions(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.list_versions( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_versions(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.list_versions( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.list_versions( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish(self, client: Courier) -> None: + template = client.journeys.templates.publish( + notification_id="x", + template_id="x", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.publish( + notification_id="x", + template_id="x", + version="v321669910225", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_publish(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.publish( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_publish(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.publish( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert template is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_publish(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.publish( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.publish( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_content(self, client: Courier) -> None: + template = client.journeys.templates.put_content( + notification_id="x", + template_id="x", + content={"elements": [{}]}, + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_content_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.put_content( + notification_id="x", + template_id="x", + content={ + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_put_content(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.put_content( + notification_id="x", + template_id="x", + content={"elements": [{}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_put_content(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.put_content( + notification_id="x", + template_id="x", + content={"elements": [{}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_put_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.put_content( + notification_id="x", + template_id="", + content={"elements": [{}]}, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.put_content( + notification_id="", + template_id="x", + content={"elements": [{}]}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_locale(self, client: Courier) -> None: + template = client.journeys.templates.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_locale_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_put_locale(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_put_locale(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_put_locale(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.put_locale( + locale_id="x", + template_id="", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.put_locale( + locale_id="x", + template_id="x", + notification_id="", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale_id` but received ''"): + client.journeys.templates.with_raw_response.put_locale( + locale_id="", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + template = client.journeys.templates.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + } + ], + "version": "2022-01-01", + "scope": "default", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + state="state", + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.replace( + notification_id="x", + template_id="", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.replace( + notification_id="", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_content(self, client: Courier) -> None: + template = client.journeys.templates.retrieve_content( + notification_id="x", + template_id="x", + ) + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_content_with_all_params(self, client: Courier) -> None: + template = client.journeys.templates.retrieve_content( + notification_id="x", + template_id="x", + version="version", + ) + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve_content(self, client: Courier) -> None: + response = client.journeys.templates.with_raw_response.retrieve_content( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve_content(self, client: Courier) -> None: + with client.journeys.templates.with_streaming_response.retrieve_content( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.templates.with_raw_response.retrieve_content( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + client.journeys.templates.with_raw_response.retrieve_content( + notification_id="", + template_id="x", + ) + + +class TestAsyncTemplates: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + } + ], + "version": "2022-01-01", + "scope": "default", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + provider_key="x", + state="state", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.create( + template_id="x", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_create(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.create( + template_id="", + channel="email", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome email", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.retrieve( + notification_id="x", + template_id="x", + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.retrieve( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.retrieve( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.retrieve( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.retrieve( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.list( + template_id="x", + ) + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.list( + template_id="x", + cursor="cursor", + limit=1, + ) + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.list( + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.list( + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(JourneyTemplateListResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.list( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.archive( + notification_id="x", + template_id="x", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.archive( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.archive( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert template is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.archive( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.archive( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_versions(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.list_versions( + notification_id="x", + template_id="x", + ) + assert_matches_type(NotificationTemplateVersionListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_versions(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.list_versions( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_versions(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.list_versions( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_versions(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.list_versions( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.list_versions( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.publish( + notification_id="x", + template_id="x", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.publish( + notification_id="x", + template_id="x", + version="v321669910225", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_publish(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.publish( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_publish(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.publish( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert template is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_publish(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.publish( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.publish( + notification_id="", + template_id="x", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_content(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.put_content( + notification_id="x", + template_id="x", + content={"elements": [{}]}, + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_content_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.put_content( + notification_id="x", + template_id="x", + content={ + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_put_content(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.put_content( + notification_id="x", + template_id="x", + content={"elements": [{}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_put_content(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.put_content( + notification_id="x", + template_id="x", + content={"elements": [{}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_put_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.put_content( + notification_id="x", + template_id="", + content={"elements": [{}]}, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.put_content( + notification_id="", + template_id="x", + content={"elements": [{}]}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_locale(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_locale_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_put_locale(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_put_locale(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.put_locale( + locale_id="x", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(NotificationContentMutationResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_put_locale(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.put_locale( + locale_id="x", + template_id="", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.put_locale( + locale_id="x", + template_id="x", + notification_id="", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale_id` but received ''"): + await async_client.journeys.templates.with_raw_response.put_locale( + locale_id="", + template_id="x", + notification_id="x", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + } + ], + "version": "2022-01-01", + "scope": "default", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + state="state", + ) + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.replace( + notification_id="x", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(JourneyTemplateGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.replace( + notification_id="x", + template_id="", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.replace( + notification_id="", + template_id="x", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "name", + "subscription": {"topic_id": "topic_id"}, + "tags": ["string"], + }, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_content(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.retrieve_content( + notification_id="x", + template_id="x", + ) + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_content_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.journeys.templates.retrieve_content( + notification_id="x", + template_id="x", + version="version", + ) + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve_content(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.templates.with_raw_response.retrieve_content( + notification_id="x", + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve_content(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.templates.with_streaming_response.retrieve_content( + notification_id="x", + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(NotificationContentGetResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.templates.with_raw_response.retrieve_content( + notification_id="x", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `notification_id` but received ''"): + await async_client.journeys.templates.with_raw_response.retrieve_content( + notification_id="", + template_id="x", + ) diff --git a/tests/api_resources/lists/__init__.py b/tests/api_resources/lists/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/lists/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/lists/test_subscriptions.py b/tests/api_resources/lists/test_subscriptions.py new file mode 100644 index 00000000..b51d1e4b --- /dev/null +++ b/tests/api_resources/lists/test_subscriptions.py @@ -0,0 +1,672 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.lists import ( + SubscriptionListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestSubscriptions: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + subscription = client.lists.subscriptions.list( + list_id="list_id", + ) + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + subscription = client.lists.subscriptions.list( + list_id="list_id", + cursor="cursor", + ) + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.lists.subscriptions.with_raw_response.list( + list_id="list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = response.parse() + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.lists.subscriptions.with_streaming_response.list( + list_id="list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = response.parse() + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.subscriptions.with_raw_response.list( + list_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add(self, client: Courier) -> None: + subscription = client.lists.subscriptions.add( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_with_all_params(self, client: Courier) -> None: + subscription = client.lists.subscriptions.add( + list_id="list_id", + recipients=[ + { + "recipient_id": "recipientId", + "preferences": { + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + } + ], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_add(self, client: Courier) -> None: + response = client.lists.subscriptions.with_raw_response.add( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_add(self, client: Courier) -> None: + with client.lists.subscriptions.with_streaming_response.add( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_add(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.subscriptions.with_raw_response.add( + list_id="", + recipients=[{"recipient_id": "recipientId"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_subscribe(self, client: Courier) -> None: + subscription = client.lists.subscriptions.subscribe( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_subscribe(self, client: Courier) -> None: + response = client.lists.subscriptions.with_raw_response.subscribe( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_subscribe(self, client: Courier) -> None: + with client.lists.subscriptions.with_streaming_response.subscribe( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_subscribe(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.subscriptions.with_raw_response.subscribe( + list_id="", + recipients=[{"recipient_id": "recipientId"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_subscribe_user(self, client: Courier) -> None: + subscription = client.lists.subscriptions.subscribe_user( + user_id="user_id", + list_id="list_id", + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_subscribe_user_with_all_params(self, client: Courier) -> None: + subscription = client.lists.subscriptions.subscribe_user( + user_id="user_id", + list_id="list_id", + preferences={ + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_subscribe_user(self, client: Courier) -> None: + response = client.lists.subscriptions.with_raw_response.subscribe_user( + user_id="user_id", + list_id="list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_subscribe_user(self, client: Courier) -> None: + with client.lists.subscriptions.with_streaming_response.subscribe_user( + user_id="user_id", + list_id="list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_subscribe_user(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.subscriptions.with_raw_response.subscribe_user( + user_id="user_id", + list_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.lists.subscriptions.with_raw_response.subscribe_user( + user_id="", + list_id="list_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_unsubscribe_user(self, client: Courier) -> None: + subscription = client.lists.subscriptions.unsubscribe_user( + user_id="user_id", + list_id="list_id", + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_unsubscribe_user(self, client: Courier) -> None: + response = client.lists.subscriptions.with_raw_response.unsubscribe_user( + user_id="user_id", + list_id="list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_unsubscribe_user(self, client: Courier) -> None: + with client.lists.subscriptions.with_streaming_response.unsubscribe_user( + user_id="user_id", + list_id="list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_unsubscribe_user(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.subscriptions.with_raw_response.unsubscribe_user( + user_id="user_id", + list_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.lists.subscriptions.with_raw_response.unsubscribe_user( + user_id="", + list_id="list_id", + ) + + +class TestAsyncSubscriptions: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.list( + list_id="list_id", + ) + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.list( + list_id="list_id", + cursor="cursor", + ) + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.subscriptions.with_raw_response.list( + list_id="list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = await response.parse() + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.lists.subscriptions.with_streaming_response.list( + list_id="list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = await response.parse() + assert_matches_type(SubscriptionListResponse, subscription, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.list( + list_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.add( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_with_all_params(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.add( + list_id="list_id", + recipients=[ + { + "recipient_id": "recipientId", + "preferences": { + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + } + ], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_add(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.subscriptions.with_raw_response.add( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = await response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_add(self, async_client: AsyncCourier) -> None: + async with async_client.lists.subscriptions.with_streaming_response.add( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = await response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_add(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.add( + list_id="", + recipients=[{"recipient_id": "recipientId"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_subscribe(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.subscribe( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_subscribe(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.subscriptions.with_raw_response.subscribe( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = await response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_subscribe(self, async_client: AsyncCourier) -> None: + async with async_client.lists.subscriptions.with_streaming_response.subscribe( + list_id="list_id", + recipients=[{"recipient_id": "recipientId"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = await response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_subscribe(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.subscribe( + list_id="", + recipients=[{"recipient_id": "recipientId"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_subscribe_user(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.subscribe_user( + user_id="user_id", + list_id="list_id", + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_subscribe_user_with_all_params(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.subscribe_user( + user_id="user_id", + list_id="list_id", + preferences={ + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_subscribe_user(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.subscriptions.with_raw_response.subscribe_user( + user_id="user_id", + list_id="list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = await response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_subscribe_user(self, async_client: AsyncCourier) -> None: + async with async_client.lists.subscriptions.with_streaming_response.subscribe_user( + user_id="user_id", + list_id="list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = await response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_subscribe_user(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.subscribe_user( + user_id="user_id", + list_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.subscribe_user( + user_id="", + list_id="list_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_unsubscribe_user(self, async_client: AsyncCourier) -> None: + subscription = await async_client.lists.subscriptions.unsubscribe_user( + user_id="user_id", + list_id="list_id", + ) + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_unsubscribe_user(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.subscriptions.with_raw_response.unsubscribe_user( + user_id="user_id", + list_id="list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + subscription = await response.parse() + assert subscription is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_unsubscribe_user(self, async_client: AsyncCourier) -> None: + async with async_client.lists.subscriptions.with_streaming_response.unsubscribe_user( + user_id="user_id", + list_id="list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + subscription = await response.parse() + assert subscription is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_unsubscribe_user(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.unsubscribe_user( + user_id="user_id", + list_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.lists.subscriptions.with_raw_response.unsubscribe_user( + user_id="", + list_id="list_id", + ) diff --git a/tests/api_resources/notifications/__init__.py b/tests/api_resources/notifications/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/notifications/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/notifications/test_checks.py b/tests/api_resources/notifications/test_checks.py new file mode 100644 index 00000000..42b2c4e1 --- /dev/null +++ b/tests/api_resources/notifications/test_checks.py @@ -0,0 +1,406 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.notifications import CheckListResponse, CheckUpdateResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestChecks: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + check = client.notifications.checks.update( + submission_id="submissionId", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + assert_matches_type(CheckUpdateResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.notifications.checks.with_raw_response.update( + submission_id="submissionId", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + check = response.parse() + assert_matches_type(CheckUpdateResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.notifications.checks.with_streaming_response.update( + submission_id="submissionId", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + check = response.parse() + assert_matches_type(CheckUpdateResponse, check, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.checks.with_raw_response.update( + submission_id="submissionId", + id="", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `submission_id` but received ''"): + client.notifications.checks.with_raw_response.update( + submission_id="", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + check = client.notifications.checks.list( + submission_id="submissionId", + id="id", + ) + assert_matches_type(CheckListResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.notifications.checks.with_raw_response.list( + submission_id="submissionId", + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + check = response.parse() + assert_matches_type(CheckListResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.notifications.checks.with_streaming_response.list( + submission_id="submissionId", + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + check = response.parse() + assert_matches_type(CheckListResponse, check, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.checks.with_raw_response.list( + submission_id="submissionId", + id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `submission_id` but received ''"): + client.notifications.checks.with_raw_response.list( + submission_id="", + id="id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + check = client.notifications.checks.delete( + submission_id="submissionId", + id="id", + ) + assert check is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.notifications.checks.with_raw_response.delete( + submission_id="submissionId", + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + check = response.parse() + assert check is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.notifications.checks.with_streaming_response.delete( + submission_id="submissionId", + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + check = response.parse() + assert check is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.checks.with_raw_response.delete( + submission_id="submissionId", + id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `submission_id` but received ''"): + client.notifications.checks.with_raw_response.delete( + submission_id="", + id="id", + ) + + +class TestAsyncChecks: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + check = await async_client.notifications.checks.update( + submission_id="submissionId", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + assert_matches_type(CheckUpdateResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.checks.with_raw_response.update( + submission_id="submissionId", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + check = await response.parse() + assert_matches_type(CheckUpdateResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.checks.with_streaming_response.update( + submission_id="submissionId", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + check = await response.parse() + assert_matches_type(CheckUpdateResponse, check, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.checks.with_raw_response.update( + submission_id="submissionId", + id="", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `submission_id` but received ''"): + await async_client.notifications.checks.with_raw_response.update( + submission_id="", + id="id", + checks=[ + { + "id": "id", + "status": "RESOLVED", + "type": "custom", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + check = await async_client.notifications.checks.list( + submission_id="submissionId", + id="id", + ) + assert_matches_type(CheckListResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.checks.with_raw_response.list( + submission_id="submissionId", + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + check = await response.parse() + assert_matches_type(CheckListResponse, check, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.checks.with_streaming_response.list( + submission_id="submissionId", + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + check = await response.parse() + assert_matches_type(CheckListResponse, check, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.checks.with_raw_response.list( + submission_id="submissionId", + id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `submission_id` but received ''"): + await async_client.notifications.checks.with_raw_response.list( + submission_id="", + id="id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + check = await async_client.notifications.checks.delete( + submission_id="submissionId", + id="id", + ) + assert check is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.checks.with_raw_response.delete( + submission_id="submissionId", + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + check = await response.parse() + assert check is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.checks.with_streaming_response.delete( + submission_id="submissionId", + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + check = await response.parse() + assert check is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.checks.with_raw_response.delete( + submission_id="submissionId", + id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `submission_id` but received ''"): + await async_client.notifications.checks.with_raw_response.delete( + submission_id="", + id="id", + ) diff --git a/tests/api_resources/profiles/__init__.py b/tests/api_resources/profiles/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/profiles/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/profiles/test_lists.py b/tests/api_resources/profiles/test_lists.py new file mode 100644 index 00000000..d7458b67 --- /dev/null +++ b/tests/api_resources/profiles/test_lists.py @@ -0,0 +1,388 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.profiles import ( + ListDeleteResponse, + ListRetrieveResponse, + ListSubscribeResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestLists: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + list_ = client.profiles.lists.retrieve( + user_id="user_id", + ) + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_with_all_params(self, client: Courier) -> None: + list_ = client.profiles.lists.retrieve( + user_id="user_id", + cursor="cursor", + ) + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.profiles.lists.with_raw_response.retrieve( + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.profiles.lists.with_streaming_response.retrieve( + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.lists.with_raw_response.retrieve( + user_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + list_ = client.profiles.lists.delete( + "user_id", + ) + assert_matches_type(ListDeleteResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.profiles.lists.with_raw_response.delete( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert_matches_type(ListDeleteResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.profiles.lists.with_streaming_response.delete( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert_matches_type(ListDeleteResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.lists.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_subscribe(self, client: Courier) -> None: + list_ = client.profiles.lists.subscribe( + user_id="user_id", + lists=[{"list_id": "listId"}], + ) + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_subscribe_with_all_params(self, client: Courier) -> None: + list_ = client.profiles.lists.subscribe( + user_id="user_id", + lists=[ + { + "list_id": "listId", + "preferences": { + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + } + ], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_subscribe(self, client: Courier) -> None: + response = client.profiles.lists.with_raw_response.subscribe( + user_id="user_id", + lists=[{"list_id": "listId"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_subscribe(self, client: Courier) -> None: + with client.profiles.lists.with_streaming_response.subscribe( + user_id="user_id", + lists=[{"list_id": "listId"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_subscribe(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.lists.with_raw_response.subscribe( + user_id="", + lists=[{"list_id": "listId"}], + ) + + +class TestAsyncLists: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + list_ = await async_client.profiles.lists.retrieve( + user_id="user_id", + ) + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncCourier) -> None: + list_ = await async_client.profiles.lists.retrieve( + user_id="user_id", + cursor="cursor", + ) + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.lists.with_raw_response.retrieve( + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.lists.with_streaming_response.retrieve( + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert_matches_type(ListRetrieveResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.lists.with_raw_response.retrieve( + user_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + list_ = await async_client.profiles.lists.delete( + "user_id", + ) + assert_matches_type(ListDeleteResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.lists.with_raw_response.delete( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert_matches_type(ListDeleteResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.lists.with_streaming_response.delete( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert_matches_type(ListDeleteResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.lists.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_subscribe(self, async_client: AsyncCourier) -> None: + list_ = await async_client.profiles.lists.subscribe( + user_id="user_id", + lists=[{"list_id": "listId"}], + ) + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_subscribe_with_all_params(self, async_client: AsyncCourier) -> None: + list_ = await async_client.profiles.lists.subscribe( + user_id="user_id", + lists=[ + { + "list_id": "listId", + "preferences": { + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + } + ], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_subscribe(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.lists.with_raw_response.subscribe( + user_id="user_id", + lists=[{"list_id": "listId"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_subscribe(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.lists.with_streaming_response.subscribe( + user_id="user_id", + lists=[{"list_id": "listId"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert_matches_type(ListSubscribeResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_subscribe(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.lists.with_raw_response.subscribe( + user_id="", + lists=[{"list_id": "listId"}], + ) diff --git a/tests/api_resources/providers/__init__.py b/tests/api_resources/providers/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/providers/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/providers/test_catalog.py b/tests/api_resources/providers/test_catalog.py new file mode 100644 index 00000000..8d25683e --- /dev/null +++ b/tests/api_resources/providers/test_catalog.py @@ -0,0 +1,100 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.providers import CatalogListResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestCatalog: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + catalog = client.providers.catalog.list() + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + catalog = client.providers.catalog.list( + channel="channel", + keys="keys", + name="name", + ) + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.providers.catalog.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + catalog = response.parse() + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.providers.catalog.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + catalog = response.parse() + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncCatalog: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + catalog = await async_client.providers.catalog.list() + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + catalog = await async_client.providers.catalog.list( + channel="channel", + keys="keys", + name="name", + ) + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.providers.catalog.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + catalog = await response.parse() + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.providers.catalog.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + catalog = await response.parse() + assert_matches_type(CatalogListResponse, catalog, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/tenants/__init__.py b/tests/api_resources/tenants/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/tenants/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/tenants/preferences/__init__.py b/tests/api_resources/tenants/preferences/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/tenants/preferences/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/tenants/preferences/test_items.py b/tests/api_resources/tenants/preferences/test_items.py new file mode 100644 index 00000000..5da4429d --- /dev/null +++ b/tests/api_resources/tenants/preferences/test_items.py @@ -0,0 +1,264 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestItems: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + item = client.tenants.preferences.items.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + ) + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_with_all_params(self, client: Courier) -> None: + item = client.tenants.preferences.items.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + custom_routing=["inbox"], + has_custom_routing=True, + ) + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.tenants.preferences.items.with_raw_response.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + item = response.parse() + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.tenants.preferences.items.with_streaming_response.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + item = response.parse() + assert item is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.preferences.items.with_raw_response.update( + topic_id="topic_id", + tenant_id="", + status="OPTED_IN", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.tenants.preferences.items.with_raw_response.update( + topic_id="", + tenant_id="tenant_id", + status="OPTED_IN", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + item = client.tenants.preferences.items.delete( + topic_id="topic_id", + tenant_id="tenant_id", + ) + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.tenants.preferences.items.with_raw_response.delete( + topic_id="topic_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + item = response.parse() + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.tenants.preferences.items.with_streaming_response.delete( + topic_id="topic_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + item = response.parse() + assert item is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.preferences.items.with_raw_response.delete( + topic_id="topic_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.tenants.preferences.items.with_raw_response.delete( + topic_id="", + tenant_id="tenant_id", + ) + + +class TestAsyncItems: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + item = await async_client.tenants.preferences.items.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + ) + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncCourier) -> None: + item = await async_client.tenants.preferences.items.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + custom_routing=["inbox"], + has_custom_routing=True, + ) + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.preferences.items.with_raw_response.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + item = await response.parse() + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.preferences.items.with_streaming_response.update( + topic_id="topic_id", + tenant_id="tenant_id", + status="OPTED_IN", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + item = await response.parse() + assert item is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.preferences.items.with_raw_response.update( + topic_id="topic_id", + tenant_id="", + status="OPTED_IN", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.tenants.preferences.items.with_raw_response.update( + topic_id="", + tenant_id="tenant_id", + status="OPTED_IN", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + item = await async_client.tenants.preferences.items.delete( + topic_id="topic_id", + tenant_id="tenant_id", + ) + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.preferences.items.with_raw_response.delete( + topic_id="topic_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + item = await response.parse() + assert item is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.preferences.items.with_streaming_response.delete( + topic_id="topic_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + item = await response.parse() + assert item is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.preferences.items.with_raw_response.delete( + topic_id="topic_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.tenants.preferences.items.with_raw_response.delete( + topic_id="", + tenant_id="tenant_id", + ) diff --git a/tests/api_resources/tenants/templates/__init__.py b/tests/api_resources/tenants/templates/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/tenants/templates/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/tenants/templates/test_versions.py b/tests/api_resources/tenants/templates/test_versions.py new file mode 100644 index 00000000..02671635 --- /dev/null +++ b/tests/api_resources/tenants/templates/test_versions.py @@ -0,0 +1,152 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import BaseTemplateTenantAssociation + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestVersions: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + version = client.tenants.templates.versions.retrieve( + version="version", + tenant_id="tenant_id", + template_id="template_id", + ) + assert_matches_type(BaseTemplateTenantAssociation, version, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.tenants.templates.versions.with_raw_response.retrieve( + version="version", + tenant_id="tenant_id", + template_id="template_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + version = response.parse() + assert_matches_type(BaseTemplateTenantAssociation, version, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.tenants.templates.versions.with_streaming_response.retrieve( + version="version", + tenant_id="tenant_id", + template_id="template_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + version = response.parse() + assert_matches_type(BaseTemplateTenantAssociation, version, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.templates.versions.with_raw_response.retrieve( + version="version", + tenant_id="", + template_id="template_id", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.tenants.templates.versions.with_raw_response.retrieve( + version="version", + tenant_id="tenant_id", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `version` but received ''"): + client.tenants.templates.versions.with_raw_response.retrieve( + version="", + tenant_id="tenant_id", + template_id="template_id", + ) + + +class TestAsyncVersions: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + version = await async_client.tenants.templates.versions.retrieve( + version="version", + tenant_id="tenant_id", + template_id="template_id", + ) + assert_matches_type(BaseTemplateTenantAssociation, version, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.templates.versions.with_raw_response.retrieve( + version="version", + tenant_id="tenant_id", + template_id="template_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + version = await response.parse() + assert_matches_type(BaseTemplateTenantAssociation, version, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.templates.versions.with_streaming_response.retrieve( + version="version", + tenant_id="tenant_id", + template_id="template_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + version = await response.parse() + assert_matches_type(BaseTemplateTenantAssociation, version, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.templates.versions.with_raw_response.retrieve( + version="version", + tenant_id="", + template_id="template_id", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.tenants.templates.versions.with_raw_response.retrieve( + version="version", + tenant_id="tenant_id", + template_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `version` but received ''"): + await async_client.tenants.templates.versions.with_raw_response.retrieve( + version="", + tenant_id="tenant_id", + template_id="template_id", + ) diff --git a/tests/api_resources/tenants/test_templates.py b/tests/api_resources/tenants/test_templates.py new file mode 100644 index 00000000..6a9c7e48 --- /dev/null +++ b/tests/api_resources/tenants/test_templates.py @@ -0,0 +1,763 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + PutTenantTemplateResponse, + BaseTemplateTenantAssociation, + PostTenantTemplatePublishResponse, +) +from courier.types.tenants import ( + TemplateListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTemplates: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + template = client.tenants.templates.retrieve( + template_id="template_id", + tenant_id="tenant_id", + ) + assert_matches_type(BaseTemplateTenantAssociation, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.tenants.templates.with_raw_response.retrieve( + template_id="template_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(BaseTemplateTenantAssociation, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.tenants.templates.with_streaming_response.retrieve( + template_id="template_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(BaseTemplateTenantAssociation, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.templates.with_raw_response.retrieve( + template_id="template_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.tenants.templates.with_raw_response.retrieve( + template_id="", + tenant_id="tenant_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + template = client.tenants.templates.list( + tenant_id="tenant_id", + ) + assert_matches_type(TemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + template = client.tenants.templates.list( + tenant_id="tenant_id", + cursor="cursor", + limit=0, + ) + assert_matches_type(TemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.tenants.templates.with_raw_response.list( + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(TemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.tenants.templates.with_streaming_response.list( + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(TemplateListResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.templates.with_raw_response.list( + tenant_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + template = client.tenants.templates.delete( + template_id="template_id", + tenant_id="tenant_id", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.tenants.templates.with_raw_response.delete( + template_id="template_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.tenants.templates.with_streaming_response.delete( + template_id="template_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert template is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.templates.with_raw_response.delete( + template_id="template_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.tenants.templates.with_raw_response.delete( + template_id="", + tenant_id="tenant_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish(self, client: Courier) -> None: + template = client.tenants.templates.publish( + template_id="template_id", + tenant_id="tenant_id", + ) + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish_with_all_params(self, client: Courier) -> None: + template = client.tenants.templates.publish( + template_id="template_id", + tenant_id="tenant_id", + version="version", + ) + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_publish(self, client: Courier) -> None: + response = client.tenants.templates.with_raw_response.publish( + template_id="template_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_publish(self, client: Courier) -> None: + with client.tenants.templates.with_streaming_response.publish( + template_id="template_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_publish(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.templates.with_raw_response.publish( + template_id="template_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.tenants.templates.with_raw_response.publish( + template_id="", + tenant_id="tenant_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + template = client.tenants.templates.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + template = client.tenants.templates.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + } + ], + "version": "version", + }, + "channels": { + "foo": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["string"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + "providers": { + "foo": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "timeouts": 0, + } + }, + "routing": { + "channels": ["string"], + "method": "all", + }, + }, + published=True, + ) + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.tenants.templates.with_raw_response.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = response.parse() + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.tenants.templates.with_streaming_response.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = response.parse() + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.templates.with_raw_response.replace( + template_id="template_id", + tenant_id="", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.tenants.templates.with_raw_response.replace( + template_id="", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + + +class TestAsyncTemplates: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.retrieve( + template_id="template_id", + tenant_id="tenant_id", + ) + assert_matches_type(BaseTemplateTenantAssociation, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.templates.with_raw_response.retrieve( + template_id="template_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(BaseTemplateTenantAssociation, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.templates.with_streaming_response.retrieve( + template_id="template_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(BaseTemplateTenantAssociation, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.templates.with_raw_response.retrieve( + template_id="template_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.tenants.templates.with_raw_response.retrieve( + template_id="", + tenant_id="tenant_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.list( + tenant_id="tenant_id", + ) + assert_matches_type(TemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.list( + tenant_id="tenant_id", + cursor="cursor", + limit=0, + ) + assert_matches_type(TemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.templates.with_raw_response.list( + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(TemplateListResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.templates.with_streaming_response.list( + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(TemplateListResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.templates.with_raw_response.list( + tenant_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.delete( + template_id="template_id", + tenant_id="tenant_id", + ) + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.templates.with_raw_response.delete( + template_id="template_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert template is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.templates.with_streaming_response.delete( + template_id="template_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert template is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.templates.with_raw_response.delete( + template_id="template_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.tenants.templates.with_raw_response.delete( + template_id="", + tenant_id="tenant_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.publish( + template_id="template_id", + tenant_id="tenant_id", + ) + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.publish( + template_id="template_id", + tenant_id="tenant_id", + version="version", + ) + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_publish(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.templates.with_raw_response.publish( + template_id="template_id", + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_publish(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.templates.with_streaming_response.publish( + template_id="template_id", + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(PostTenantTemplatePublishResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_publish(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.templates.with_raw_response.publish( + template_id="template_id", + tenant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.tenants.templates.with_raw_response.publish( + template_id="", + tenant_id="tenant_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + template = await async_client.tenants.templates.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + } + ], + "version": "version", + }, + "channels": { + "foo": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["string"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + "providers": { + "foo": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "timeouts": 0, + } + }, + "routing": { + "channels": ["string"], + "method": "all", + }, + }, + published=True, + ) + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.templates.with_raw_response.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + template = await response.parse() + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.templates.with_streaming_response.replace( + template_id="template_id", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + template = await response.parse() + assert_matches_type(PutTenantTemplateResponse, template, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.templates.with_raw_response.replace( + template_id="template_id", + tenant_id="", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.tenants.templates.with_raw_response.replace( + template_id="", + tenant_id="tenant_id", + template={ + "content": { + "elements": [{}], + "version": "version", + } + }, + ) diff --git a/tests/api_resources/test_audiences.py b/tests/api_resources/test_audiences.py new file mode 100644 index 00000000..8f69d408 --- /dev/null +++ b/tests/api_resources/test_audiences.py @@ -0,0 +1,499 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + Audience, + AudienceListResponse, + AudienceUpdateResponse, + AudienceListMembersResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestAudiences: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + audience = client.audiences.retrieve( + "audience_id", + ) + assert_matches_type(Audience, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.audiences.with_raw_response.retrieve( + "audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = response.parse() + assert_matches_type(Audience, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.audiences.with_streaming_response.retrieve( + "audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = response.parse() + assert_matches_type(Audience, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + client.audiences.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + audience = client.audiences.update( + audience_id="audience_id", + ) + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_with_all_params(self, client: Courier) -> None: + audience = client.audiences.update( + audience_id="audience_id", + description="description", + filter={ + "filters": [ + { + "operator": "operator", + "filters": [], + "path": "path", + "value": "value", + } + ], + "operator": "AND", + }, + name="name", + operator="AND", + ) + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.audiences.with_raw_response.update( + audience_id="audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = response.parse() + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.audiences.with_streaming_response.update( + audience_id="audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = response.parse() + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + client.audiences.with_raw_response.update( + audience_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + audience = client.audiences.list() + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + audience = client.audiences.list( + cursor="cursor", + ) + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.audiences.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = response.parse() + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.audiences.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = response.parse() + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + audience = client.audiences.delete( + "audience_id", + ) + assert audience is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.audiences.with_raw_response.delete( + "audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = response.parse() + assert audience is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.audiences.with_streaming_response.delete( + "audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = response.parse() + assert audience is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + client.audiences.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_members(self, client: Courier) -> None: + audience = client.audiences.list_members( + audience_id="audience_id", + ) + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_members_with_all_params(self, client: Courier) -> None: + audience = client.audiences.list_members( + audience_id="audience_id", + cursor="cursor", + ) + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_members(self, client: Courier) -> None: + response = client.audiences.with_raw_response.list_members( + audience_id="audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = response.parse() + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_members(self, client: Courier) -> None: + with client.audiences.with_streaming_response.list_members( + audience_id="audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = response.parse() + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_members(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + client.audiences.with_raw_response.list_members( + audience_id="", + ) + + +class TestAsyncAudiences: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.retrieve( + "audience_id", + ) + assert_matches_type(Audience, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.audiences.with_raw_response.retrieve( + "audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = await response.parse() + assert_matches_type(Audience, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.audiences.with_streaming_response.retrieve( + "audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = await response.parse() + assert_matches_type(Audience, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + await async_client.audiences.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.update( + audience_id="audience_id", + ) + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.update( + audience_id="audience_id", + description="description", + filter={ + "filters": [ + { + "operator": "operator", + "filters": [], + "path": "path", + "value": "value", + } + ], + "operator": "AND", + }, + name="name", + operator="AND", + ) + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.audiences.with_raw_response.update( + audience_id="audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = await response.parse() + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.audiences.with_streaming_response.update( + audience_id="audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = await response.parse() + assert_matches_type(AudienceUpdateResponse, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + await async_client.audiences.with_raw_response.update( + audience_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.list() + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.list( + cursor="cursor", + ) + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.audiences.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = await response.parse() + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.audiences.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = await response.parse() + assert_matches_type(AudienceListResponse, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.delete( + "audience_id", + ) + assert audience is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.audiences.with_raw_response.delete( + "audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = await response.parse() + assert audience is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.audiences.with_streaming_response.delete( + "audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = await response.parse() + assert audience is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + await async_client.audiences.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_members(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.list_members( + audience_id="audience_id", + ) + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_members_with_all_params(self, async_client: AsyncCourier) -> None: + audience = await async_client.audiences.list_members( + audience_id="audience_id", + cursor="cursor", + ) + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_members(self, async_client: AsyncCourier) -> None: + response = await async_client.audiences.with_raw_response.list_members( + audience_id="audience_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audience = await response.parse() + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_members(self, async_client: AsyncCourier) -> None: + async with async_client.audiences.with_streaming_response.list_members( + audience_id="audience_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audience = await response.parse() + assert_matches_type(AudienceListMembersResponse, audience, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_members(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audience_id` but received ''"): + await async_client.audiences.with_raw_response.list_members( + audience_id="", + ) diff --git a/tests/api_resources/test_audit_events.py b/tests/api_resources/test_audit_events.py new file mode 100644 index 00000000..5528746e --- /dev/null +++ b/tests/api_resources/test_audit_events.py @@ -0,0 +1,180 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import AuditEvent, AuditEventListResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestAuditEvents: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + audit_event = client.audit_events.retrieve( + "audit-event-id", + ) + assert_matches_type(AuditEvent, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.audit_events.with_raw_response.retrieve( + "audit-event-id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audit_event = response.parse() + assert_matches_type(AuditEvent, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.audit_events.with_streaming_response.retrieve( + "audit-event-id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audit_event = response.parse() + assert_matches_type(AuditEvent, audit_event, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audit_event_id` but received ''"): + client.audit_events.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + audit_event = client.audit_events.list() + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + audit_event = client.audit_events.list( + cursor="cursor", + ) + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.audit_events.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audit_event = response.parse() + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.audit_events.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audit_event = response.parse() + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncAuditEvents: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + audit_event = await async_client.audit_events.retrieve( + "audit-event-id", + ) + assert_matches_type(AuditEvent, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.audit_events.with_raw_response.retrieve( + "audit-event-id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audit_event = await response.parse() + assert_matches_type(AuditEvent, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.audit_events.with_streaming_response.retrieve( + "audit-event-id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audit_event = await response.parse() + assert_matches_type(AuditEvent, audit_event, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `audit_event_id` but received ''"): + await async_client.audit_events.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + audit_event = await async_client.audit_events.list() + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + audit_event = await async_client.audit_events.list( + cursor="cursor", + ) + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.audit_events.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + audit_event = await response.parse() + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.audit_events.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + audit_event = await response.parse() + assert_matches_type(AuditEventListResponse, audit_event, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_auth.py b/tests/api_resources/test_auth.py new file mode 100644 index 00000000..ac27998c --- /dev/null +++ b/tests/api_resources/test_auth.py @@ -0,0 +1,98 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import AuthIssueTokenResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestAuth: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_issue_token(self, client: Courier) -> None: + auth = client.auth.issue_token( + expires_in="$YOUR_NUMBER days", + scope="user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", + ) + assert_matches_type(AuthIssueTokenResponse, auth, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_issue_token(self, client: Courier) -> None: + response = client.auth.with_raw_response.issue_token( + expires_in="$YOUR_NUMBER days", + scope="user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + auth = response.parse() + assert_matches_type(AuthIssueTokenResponse, auth, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_issue_token(self, client: Courier) -> None: + with client.auth.with_streaming_response.issue_token( + expires_in="$YOUR_NUMBER days", + scope="user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + auth = response.parse() + assert_matches_type(AuthIssueTokenResponse, auth, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncAuth: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_issue_token(self, async_client: AsyncCourier) -> None: + auth = await async_client.auth.issue_token( + expires_in="$YOUR_NUMBER days", + scope="user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", + ) + assert_matches_type(AuthIssueTokenResponse, auth, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_issue_token(self, async_client: AsyncCourier) -> None: + response = await async_client.auth.with_raw_response.issue_token( + expires_in="$YOUR_NUMBER days", + scope="user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + auth = await response.parse() + assert_matches_type(AuthIssueTokenResponse, auth, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_issue_token(self, async_client: AsyncCourier) -> None: + async with async_client.auth.with_streaming_response.issue_token( + expires_in="$YOUR_NUMBER days", + scope="user_id:$YOUR_USER_ID write:user-tokens inbox:read:messages inbox:write:events read:preferences write:preferences read:brands", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + auth = await response.parse() + assert_matches_type(AuthIssueTokenResponse, auth, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_automations.py b/tests/api_resources/test_automations.py new file mode 100644 index 00000000..7f1b9587 --- /dev/null +++ b/tests/api_resources/test_automations.py @@ -0,0 +1,98 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import AutomationTemplateListResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestAutomations: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + automation = client.automations.list() + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + automation = client.automations.list( + cursor="cursor", + version="published", + ) + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.automations.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + automation = response.parse() + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.automations.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + automation = response.parse() + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncAutomations: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + automation = await async_client.automations.list() + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + automation = await async_client.automations.list( + cursor="cursor", + version="published", + ) + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.automations.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + automation = await response.parse() + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.automations.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + automation = await response.parse() + assert_matches_type(AutomationTemplateListResponse, automation, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_brands.py b/tests/api_resources/test_brands.py new file mode 100644 index 00000000..dd548d5c --- /dev/null +++ b/tests/api_resources/test_brands.py @@ -0,0 +1,753 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + Brand, + BrandListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestBrands: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + brand = client.brands.create( + name="My Brand", + settings={}, + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + brand = client.brands.create( + name="My Brand", + settings={ + "colors": { + "primary": "#9D3789", + "secondary": "#FFFFFF", + }, + "email": { + "footer": { + "content": "content", + "inherit_default": True, + }, + "head": { + "inherit_default": True, + "content": "content", + }, + "header": { + "logo": { + "href": "href", + "image": "image", + }, + "bar_color": "barColor", + "inherit_default": True, + }, + "template_override": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + "mjml": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + }, + "footer_background_color": "footerBackgroundColor", + "footer_full_width": True, + }, + }, + "inapp": { + "colors": { + "primary": "primary", + "secondary": "secondary", + }, + "icons": { + "bell": "bell", + "message": "message", + }, + "widget_background": { + "bottom_color": "bottomColor", + "top_color": "topColor", + }, + "border_radius": "borderRadius", + "disable_message_icon": True, + "font_family": "fontFamily", + "placement": "top", + }, + }, + id="id", + snippets={ + "items": [ + { + "name": "name", + "value": "value", + } + ] + }, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.brands.with_raw_response.create( + name="My Brand", + settings={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.brands.with_streaming_response.create( + name="My Brand", + settings={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + brand = client.brands.retrieve( + "brand_id", + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.brands.with_raw_response.retrieve( + "brand_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.brands.with_streaming_response.retrieve( + "brand_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `brand_id` but received ''"): + client.brands.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + brand = client.brands.update( + brand_id="brand_id", + name="name", + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_with_all_params(self, client: Courier) -> None: + brand = client.brands.update( + brand_id="brand_id", + name="name", + settings={ + "colors": { + "primary": "primary", + "secondary": "secondary", + }, + "email": { + "footer": { + "content": "content", + "inherit_default": True, + }, + "head": { + "inherit_default": True, + "content": "content", + }, + "header": { + "logo": { + "href": "href", + "image": "image", + }, + "bar_color": "barColor", + "inherit_default": True, + }, + "template_override": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + "mjml": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + }, + "footer_background_color": "footerBackgroundColor", + "footer_full_width": True, + }, + }, + "inapp": { + "colors": { + "primary": "primary", + "secondary": "secondary", + }, + "icons": { + "bell": "bell", + "message": "message", + }, + "widget_background": { + "bottom_color": "bottomColor", + "top_color": "topColor", + }, + "border_radius": "borderRadius", + "disable_message_icon": True, + "font_family": "fontFamily", + "placement": "top", + }, + }, + snippets={ + "items": [ + { + "name": "name", + "value": "value", + } + ] + }, + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.brands.with_raw_response.update( + brand_id="brand_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.brands.with_streaming_response.update( + brand_id="brand_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `brand_id` but received ''"): + client.brands.with_raw_response.update( + brand_id="", + name="name", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + brand = client.brands.list() + assert_matches_type(BrandListResponse, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + brand = client.brands.list( + cursor="cursor", + ) + assert_matches_type(BrandListResponse, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.brands.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = response.parse() + assert_matches_type(BrandListResponse, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.brands.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = response.parse() + assert_matches_type(BrandListResponse, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + brand = client.brands.delete( + "brand_id", + ) + assert brand is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.brands.with_raw_response.delete( + "brand_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = response.parse() + assert brand is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.brands.with_streaming_response.delete( + "brand_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = response.parse() + assert brand is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `brand_id` but received ''"): + client.brands.with_raw_response.delete( + "", + ) + + +class TestAsyncBrands: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.create( + name="My Brand", + settings={}, + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.create( + name="My Brand", + settings={ + "colors": { + "primary": "#9D3789", + "secondary": "#FFFFFF", + }, + "email": { + "footer": { + "content": "content", + "inherit_default": True, + }, + "head": { + "inherit_default": True, + "content": "content", + }, + "header": { + "logo": { + "href": "href", + "image": "image", + }, + "bar_color": "barColor", + "inherit_default": True, + }, + "template_override": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + "mjml": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + }, + "footer_background_color": "footerBackgroundColor", + "footer_full_width": True, + }, + }, + "inapp": { + "colors": { + "primary": "primary", + "secondary": "secondary", + }, + "icons": { + "bell": "bell", + "message": "message", + }, + "widget_background": { + "bottom_color": "bottomColor", + "top_color": "topColor", + }, + "border_radius": "borderRadius", + "disable_message_icon": True, + "font_family": "fontFamily", + "placement": "top", + }, + }, + id="id", + snippets={ + "items": [ + { + "name": "name", + "value": "value", + } + ] + }, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.brands.with_raw_response.create( + name="My Brand", + settings={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = await response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.brands.with_streaming_response.create( + name="My Brand", + settings={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = await response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.retrieve( + "brand_id", + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.brands.with_raw_response.retrieve( + "brand_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = await response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.brands.with_streaming_response.retrieve( + "brand_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = await response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `brand_id` but received ''"): + await async_client.brands.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.update( + brand_id="brand_id", + name="name", + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.update( + brand_id="brand_id", + name="name", + settings={ + "colors": { + "primary": "primary", + "secondary": "secondary", + }, + "email": { + "footer": { + "content": "content", + "inherit_default": True, + }, + "head": { + "inherit_default": True, + "content": "content", + }, + "header": { + "logo": { + "href": "href", + "image": "image", + }, + "bar_color": "barColor", + "inherit_default": True, + }, + "template_override": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + "mjml": { + "enabled": True, + "background_color": "backgroundColor", + "blocks_background_color": "blocksBackgroundColor", + "footer": "footer", + "head": "head", + "header": "header", + "width": "width", + }, + "footer_background_color": "footerBackgroundColor", + "footer_full_width": True, + }, + }, + "inapp": { + "colors": { + "primary": "primary", + "secondary": "secondary", + }, + "icons": { + "bell": "bell", + "message": "message", + }, + "widget_background": { + "bottom_color": "bottomColor", + "top_color": "topColor", + }, + "border_radius": "borderRadius", + "disable_message_icon": True, + "font_family": "fontFamily", + "placement": "top", + }, + }, + snippets={ + "items": [ + { + "name": "name", + "value": "value", + } + ] + }, + ) + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.brands.with_raw_response.update( + brand_id="brand_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = await response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.brands.with_streaming_response.update( + brand_id="brand_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = await response.parse() + assert_matches_type(Brand, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `brand_id` but received ''"): + await async_client.brands.with_raw_response.update( + brand_id="", + name="name", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.list() + assert_matches_type(BrandListResponse, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.list( + cursor="cursor", + ) + assert_matches_type(BrandListResponse, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.brands.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = await response.parse() + assert_matches_type(BrandListResponse, brand, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.brands.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = await response.parse() + assert_matches_type(BrandListResponse, brand, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + brand = await async_client.brands.delete( + "brand_id", + ) + assert brand is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.brands.with_raw_response.delete( + "brand_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + brand = await response.parse() + assert brand is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.brands.with_streaming_response.delete( + "brand_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + brand = await response.parse() + assert brand is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `brand_id` but received ''"): + await async_client.brands.with_raw_response.delete( + "", + ) diff --git a/tests/api_resources/test_broadcasts.py b/tests/api_resources/test_broadcasts.py new file mode 100644 index 00000000..cc57f88c --- /dev/null +++ b/tests/api_resources/test_broadcasts.py @@ -0,0 +1,1087 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + Broadcast, + BroadcastListResponse, + NotificationContentGetResponse, + NotificationContentMutationResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestBroadcasts: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + broadcast = client.broadcasts.create( + channel="email", + name="Spring Sale Announcement", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.create( + channel="email", + name="Spring Sale Announcement", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.create( + channel="email", + name="Spring Sale Announcement", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + broadcast = client.broadcasts.retrieve( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.retrieve( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.retrieve( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + broadcast = client.broadcasts.update( + broadcast_id="broadcastId", + name="Spring Sale Announcement (v2)", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.update( + broadcast_id="broadcastId", + name="Spring Sale Announcement (v2)", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.update( + broadcast_id="broadcastId", + name="Spring Sale Announcement (v2)", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.update( + broadcast_id="", + name="Spring Sale Announcement (v2)", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + broadcast = client.broadcasts.list() + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + broadcast = client.broadcasts.list( + cursor="cursor", + limit=1, + ) + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + broadcast = client.broadcasts.archive( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.archive( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.archive( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_cancel(self, client: Courier) -> None: + broadcast = client.broadcasts.cancel( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_cancel(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.cancel( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_cancel(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.cancel( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_cancel(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.cancel( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_duplicate(self, client: Courier) -> None: + broadcast = client.broadcasts.duplicate( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_duplicate(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.duplicate( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_duplicate(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.duplicate( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_duplicate(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.duplicate( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_content(self, client: Courier) -> None: + broadcast = client.broadcasts.put_content( + broadcast_id="broadcastId", + content={"elements": [{}, {}]}, + ) + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_content_with_all_params(self, client: Courier) -> None: + broadcast = client.broadcasts.put_content( + broadcast_id="broadcastId", + content={ + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "meta", + }, + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + }, + ], + "version": "2022-01-01", + }, + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_put_content(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.put_content( + broadcast_id="broadcastId", + content={"elements": [{}, {}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_put_content(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.put_content( + broadcast_id="broadcastId", + content={"elements": [{}, {}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_put_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.put_content( + broadcast_id="", + content={"elements": [{}, {}]}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_content(self, client: Courier) -> None: + broadcast = client.broadcasts.retrieve_content( + broadcast_id="broadcastId", + ) + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_content_with_all_params(self, client: Courier) -> None: + broadcast = client.broadcasts.retrieve_content( + broadcast_id="broadcastId", + version="version", + ) + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve_content(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.retrieve_content( + broadcast_id="broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve_content(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.retrieve_content( + broadcast_id="broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.retrieve_content( + broadcast_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_schedule(self, client: Courier) -> None: + broadcast = client.broadcasts.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_schedule_with_all_params(self, client: Courier) -> None: + broadcast = client.broadcasts.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + timezone="America/New_York", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_schedule(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_schedule(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_schedule(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.schedule( + broadcast_id="", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_send(self, client: Courier) -> None: + broadcast = client.broadcasts.send( + broadcast_id="broadcastId", + recipient_id="cool-customers", + recipient_type="list", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_send(self, client: Courier) -> None: + response = client.broadcasts.with_raw_response.send( + broadcast_id="broadcastId", + recipient_id="cool-customers", + recipient_type="list", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_send(self, client: Courier) -> None: + with client.broadcasts.with_streaming_response.send( + broadcast_id="broadcastId", + recipient_id="cool-customers", + recipient_type="list", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_send(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + client.broadcasts.with_raw_response.send( + broadcast_id="", + recipient_id="cool-customers", + recipient_type="list", + ) + + +class TestAsyncBroadcasts: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.create( + channel="email", + name="Spring Sale Announcement", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.create( + channel="email", + name="Spring Sale Announcement", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.create( + channel="email", + name="Spring Sale Announcement", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.retrieve( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.retrieve( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.retrieve( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.update( + broadcast_id="broadcastId", + name="Spring Sale Announcement (v2)", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.update( + broadcast_id="broadcastId", + name="Spring Sale Announcement (v2)", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.update( + broadcast_id="broadcastId", + name="Spring Sale Announcement (v2)", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.update( + broadcast_id="", + name="Spring Sale Announcement (v2)", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.list() + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.list( + cursor="cursor", + limit=1, + ) + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(BroadcastListResponse, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.archive( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.archive( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.archive( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_cancel(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.cancel( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_cancel(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.cancel( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_cancel(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.cancel( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_cancel(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.cancel( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_duplicate(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.duplicate( + "broadcastId", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_duplicate(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.duplicate( + "broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_duplicate(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.duplicate( + "broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_duplicate(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.duplicate( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_content(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.put_content( + broadcast_id="broadcastId", + content={"elements": [{}, {}]}, + ) + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_content_with_all_params(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.put_content( + broadcast_id="broadcastId", + content={ + "elements": [ + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "meta", + }, + { + "channels": ["string"], + "if": "if", + "loop": "loop", + "ref": "ref", + "type": "text", + }, + ], + "version": "2022-01-01", + }, + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_put_content(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.put_content( + broadcast_id="broadcastId", + content={"elements": [{}, {}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_put_content(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.put_content( + broadcast_id="broadcastId", + content={"elements": [{}, {}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(NotificationContentMutationResponse, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_put_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.put_content( + broadcast_id="", + content={"elements": [{}, {}]}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_content(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.retrieve_content( + broadcast_id="broadcastId", + ) + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_content_with_all_params(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.retrieve_content( + broadcast_id="broadcastId", + version="version", + ) + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve_content(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.retrieve_content( + broadcast_id="broadcastId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve_content(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.retrieve_content( + broadcast_id="broadcastId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(NotificationContentGetResponse, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.retrieve_content( + broadcast_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_schedule(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_schedule_with_all_params(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + timezone="America/New_York", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_schedule(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_schedule(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.schedule( + broadcast_id="broadcastId", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_schedule(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.schedule( + broadcast_id="", + recipient_id="aud_01kx4h2jdafq8bk9amzvy6hbv0", + recipient_type="audience", + scheduled_to="2026-08-01T15:00:00", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_send(self, async_client: AsyncCourier) -> None: + broadcast = await async_client.broadcasts.send( + broadcast_id="broadcastId", + recipient_id="cool-customers", + recipient_type="list", + ) + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_send(self, async_client: AsyncCourier) -> None: + response = await async_client.broadcasts.with_raw_response.send( + broadcast_id="broadcastId", + recipient_id="cool-customers", + recipient_type="list", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_send(self, async_client: AsyncCourier) -> None: + async with async_client.broadcasts.with_streaming_response.send( + broadcast_id="broadcastId", + recipient_id="cool-customers", + recipient_type="list", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + broadcast = await response.parse() + assert_matches_type(Broadcast, broadcast, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_send(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `broadcast_id` but received ''"): + await async_client.broadcasts.with_raw_response.send( + broadcast_id="", + recipient_id="cool-customers", + recipient_type="list", + ) diff --git a/tests/api_resources/test_inbound.py b/tests/api_resources/test_inbound.py new file mode 100644 index 00000000..d18caeb6 --- /dev/null +++ b/tests/api_resources/test_inbound.py @@ -0,0 +1,166 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import InboundTrackEventResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestInbound: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_track_event(self, client: Courier) -> None: + inbound = client.inbound.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + ) + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_track_event_with_all_params(self, client: Courier) -> None: + inbound = client.inbound.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + user_id="1234", + ) + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_track_event(self, client: Courier) -> None: + response = client.inbound.with_raw_response.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + inbound = response.parse() + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_track_event(self, client: Courier) -> None: + with client.inbound.with_streaming_response.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + inbound = response.parse() + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncInbound: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_track_event(self, async_client: AsyncCourier) -> None: + inbound = await async_client.inbound.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + ) + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_track_event_with_all_params(self, async_client: AsyncCourier) -> None: + inbound = await async_client.inbound.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + user_id="1234", + ) + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_track_event(self, async_client: AsyncCourier) -> None: + response = await async_client.inbound.with_raw_response.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + inbound = await response.parse() + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_track_event(self, async_client: AsyncCourier) -> None: + async with async_client.inbound.with_streaming_response.track_event( + event="New Order Placed", + message_id="4c62c457-b329-4bea-9bfc-17bba86c393f", + properties={ + "order_id": "bar", + "total_orders": "bar", + "last_order_id": "bar", + }, + type="track", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + inbound = await response.parse() + assert_matches_type(InboundTrackEventResponse, inbound, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_journeys.py b/tests/api_resources/test_journeys.py new file mode 100644 index 00000000..c47fab51 --- /dev/null +++ b/tests/api_resources/test_journeys.py @@ -0,0 +1,1212 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + JourneyResponse, + JourneysListResponse, + CancelJourneyResponse, + JourneysInvokeResponse, + JourneyVersionsListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestJourneys: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + journey = client.journeys.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + }, + { + "message": {}, + "type": "send", + }, + {"type": "exit"}, + ], + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + journey = client.journeys.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + "id": "trigger-1", + "conditions": ["string", "string"], + "schema": {"foo": "bar"}, + }, + { + "message": { + "context": {"tenant_id": "x"}, + "data": {"foo": "bar"}, + "delay": { + "until": "x", + "timezone": "x", + }, + "template": "nt_01kx4h2jdafq8bk9aftxak4b40", + "to": { + "email_override": "x", + "phone_number_override": "x", + "user_id_override": "x", + }, + }, + "type": "send", + "id": "send-1", + "conditions": ["string", "string"], + "experiment": { + "bucketing_key": "x", + "variants": [ + { + "id": "x", + "template_id": "x", + "weight": 0, + "name": "name", + }, + { + "id": "x", + "template_id": "x", + "weight": 0, + "name": "name", + }, + ], + "id": "x", + "name": "name", + }, + }, + { + "type": "exit", + "id": "exit-1", + }, + ], + enabled=True, + state="DRAFT", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.journeys.with_raw_response.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + }, + { + "message": {}, + "type": "send", + }, + {"type": "exit"}, + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.journeys.with_streaming_response.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + }, + { + "message": {}, + "type": "send", + }, + {"type": "exit"}, + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + journey = client.journeys.retrieve( + template_id="x", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_with_all_params(self, client: Courier) -> None: + journey = client.journeys.retrieve( + template_id="x", + version="published", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.journeys.with_raw_response.retrieve( + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.journeys.with_streaming_response.retrieve( + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.with_raw_response.retrieve( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + journey = client.journeys.list() + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + journey = client.journeys.list( + cursor="cursor", + version="published", + ) + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.journeys.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.journeys.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + journey = client.journeys.archive( + "x", + ) + assert journey is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.journeys.with_raw_response.archive( + "x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert journey is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.journeys.with_streaming_response.archive( + "x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert journey is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_cancel_overload_1(self, client: Courier) -> None: + journey = client.journeys.cancel( + cancelation_token="x", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_cancel_with_all_params_overload_1(self, client: Courier) -> None: + journey = client.journeys.cancel( + cancelation_token="x", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_cancel_overload_1(self, client: Courier) -> None: + response = client.journeys.with_raw_response.cancel( + cancelation_token="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_cancel_overload_1(self, client: Courier) -> None: + with client.journeys.with_streaming_response.cancel( + cancelation_token="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_cancel_overload_2(self, client: Courier) -> None: + journey = client.journeys.cancel( + run_id="x", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_cancel_with_all_params_overload_2(self, client: Courier) -> None: + journey = client.journeys.cancel( + run_id="x", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_cancel_overload_2(self, client: Courier) -> None: + response = client.journeys.with_raw_response.cancel( + run_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_cancel_overload_2(self, client: Courier) -> None: + with client.journeys.with_streaming_response.cancel( + run_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_invoke(self, client: Courier) -> None: + journey = client.journeys.invoke( + template_id="templateId", + ) + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_invoke_with_all_params(self, client: Courier) -> None: + journey = client.journeys.invoke( + template_id="templateId", + data={ + "order_id": "bar", + "amount": "bar", + }, + profile={"foo": "bar"}, + user_id="user-123", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_invoke(self, client: Courier) -> None: + response = client.journeys.with_raw_response.invoke( + template_id="templateId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_invoke(self, client: Courier) -> None: + with client.journeys.with_streaming_response.invoke( + template_id="templateId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_invoke(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.with_raw_response.invoke( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_versions(self, client: Courier) -> None: + journey = client.journeys.list_versions( + "x", + ) + assert_matches_type(JourneyVersionsListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_versions(self, client: Courier) -> None: + response = client.journeys.with_raw_response.list_versions( + "x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneyVersionsListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_versions(self, client: Courier) -> None: + with client.journeys.with_streaming_response.list_versions( + "x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneyVersionsListResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_versions(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.with_raw_response.list_versions( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish(self, client: Courier) -> None: + journey = client.journeys.publish( + template_id="x", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish_with_all_params(self, client: Courier) -> None: + journey = client.journeys.publish( + template_id="x", + version="v321669910225", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_publish(self, client: Courier) -> None: + response = client.journeys.with_raw_response.publish( + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_publish(self, client: Courier) -> None: + with client.journeys.with_streaming_response.publish( + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_publish(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.with_raw_response.publish( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + journey = client.journeys.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + journey = client.journeys.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + "id": "x", + "conditions": ["string", "string"], + "schema": {"foo": "bar"}, + } + ], + enabled=True, + state="DRAFT", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.journeys.with_raw_response.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.journeys.with_streaming_response.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + client.journeys.with_raw_response.replace( + template_id="", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) + + +class TestAsyncJourneys: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + }, + { + "message": {}, + "type": "send", + }, + {"type": "exit"}, + ], + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + "id": "trigger-1", + "conditions": ["string", "string"], + "schema": {"foo": "bar"}, + }, + { + "message": { + "context": {"tenant_id": "x"}, + "data": {"foo": "bar"}, + "delay": { + "until": "x", + "timezone": "x", + }, + "template": "nt_01kx4h2jdafq8bk9aftxak4b40", + "to": { + "email_override": "x", + "phone_number_override": "x", + "user_id_override": "x", + }, + }, + "type": "send", + "id": "send-1", + "conditions": ["string", "string"], + "experiment": { + "bucketing_key": "x", + "variants": [ + { + "id": "x", + "template_id": "x", + "weight": 0, + "name": "name", + }, + { + "id": "x", + "template_id": "x", + "weight": 0, + "name": "name", + }, + ], + "id": "x", + "name": "name", + }, + }, + { + "type": "exit", + "id": "exit-1", + }, + ], + enabled=True, + state="DRAFT", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + }, + { + "message": {}, + "type": "send", + }, + {"type": "exit"}, + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.create( + name="Welcome Journey", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + }, + { + "message": {}, + "type": "send", + }, + {"type": "exit"}, + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.retrieve( + template_id="x", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.retrieve( + template_id="x", + version="published", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.retrieve( + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.retrieve( + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.with_raw_response.retrieve( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.list() + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.list( + cursor="cursor", + version="published", + ) + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneysListResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.archive( + "x", + ) + assert journey is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.archive( + "x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert journey is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.archive( + "x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert journey is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_cancel_overload_1(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.cancel( + cancelation_token="x", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_cancel_with_all_params_overload_1(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.cancel( + cancelation_token="x", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_cancel_overload_1(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.cancel( + cancelation_token="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_cancel_overload_1(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.cancel( + cancelation_token="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_cancel_overload_2(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.cancel( + run_id="x", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_cancel_with_all_params_overload_2(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.cancel( + run_id="x", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_cancel_overload_2(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.cancel( + run_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_cancel_overload_2(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.cancel( + run_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(CancelJourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_invoke(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.invoke( + template_id="templateId", + ) + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_invoke_with_all_params(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.invoke( + template_id="templateId", + data={ + "order_id": "bar", + "amount": "bar", + }, + profile={"foo": "bar"}, + user_id="user-123", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_invoke(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.invoke( + template_id="templateId", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_invoke(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.invoke( + template_id="templateId", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneysInvokeResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_invoke(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.with_raw_response.invoke( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_versions(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.list_versions( + "x", + ) + assert_matches_type(JourneyVersionsListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_versions(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.list_versions( + "x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneyVersionsListResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_versions(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.list_versions( + "x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneyVersionsListResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_versions(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.with_raw_response.list_versions( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.publish( + template_id="x", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish_with_all_params(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.publish( + template_id="x", + version="v321669910225", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_publish(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.publish( + template_id="x", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_publish(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.publish( + template_id="x", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_publish(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.with_raw_response.publish( + template_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + journey = await async_client.journeys.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + "id": "x", + "conditions": ["string", "string"], + "schema": {"foo": "bar"}, + } + ], + enabled=True, + state="DRAFT", + ) + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.journeys.with_raw_response.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.journeys.with_streaming_response.replace( + template_id="x", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + journey = await response.parse() + assert_matches_type(JourneyResponse, journey, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `template_id` but received ''"): + await async_client.journeys.with_raw_response.replace( + template_id="", + name="Welcome Journey v2", + nodes=[ + { + "trigger_type": "api-invoke", + "type": "trigger", + } + ], + ) diff --git a/tests/api_resources/test_lists.py b/tests/api_resources/test_lists.py new file mode 100644 index 00000000..3cdd6575 --- /dev/null +++ b/tests/api_resources/test_lists.py @@ -0,0 +1,512 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ListListResponse, SubscriptionList + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestLists: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + list_ = client.lists.retrieve( + "list_id", + ) + assert_matches_type(SubscriptionList, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.lists.with_raw_response.retrieve( + "list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert_matches_type(SubscriptionList, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.lists.with_streaming_response.retrieve( + "list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert_matches_type(SubscriptionList, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + list_ = client.lists.update( + list_id="list_id", + name="name", + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_with_all_params(self, client: Courier) -> None: + list_ = client.lists.update( + list_id="list_id", + name="name", + preferences={ + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.lists.with_raw_response.update( + list_id="list_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.lists.with_streaming_response.update( + list_id="list_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert list_ is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.with_raw_response.update( + list_id="", + name="name", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + list_ = client.lists.list() + assert_matches_type(ListListResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + list_ = client.lists.list( + cursor="cursor", + pattern="pattern", + ) + assert_matches_type(ListListResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.lists.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert_matches_type(ListListResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.lists.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert_matches_type(ListListResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + list_ = client.lists.delete( + "list_id", + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.lists.with_raw_response.delete( + "list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.lists.with_streaming_response.delete( + "list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert list_ is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_restore(self, client: Courier) -> None: + list_ = client.lists.restore( + "list_id", + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_restore(self, client: Courier) -> None: + response = client.lists.with_raw_response.restore( + "list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = response.parse() + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_restore(self, client: Courier) -> None: + with client.lists.with_streaming_response.restore( + "list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = response.parse() + assert list_ is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_restore(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + client.lists.with_raw_response.restore( + "", + ) + + +class TestAsyncLists: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.retrieve( + "list_id", + ) + assert_matches_type(SubscriptionList, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.with_raw_response.retrieve( + "list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert_matches_type(SubscriptionList, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.lists.with_streaming_response.retrieve( + "list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert_matches_type(SubscriptionList, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.update( + list_id="list_id", + name="name", + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.update( + list_id="list_id", + name="name", + preferences={ + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + } + }, + }, + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.with_raw_response.update( + list_id="list_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.lists.with_streaming_response.update( + list_id="list_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert list_ is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.with_raw_response.update( + list_id="", + name="name", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.list() + assert_matches_type(ListListResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.list( + cursor="cursor", + pattern="pattern", + ) + assert_matches_type(ListListResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert_matches_type(ListListResponse, list_, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.lists.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert_matches_type(ListListResponse, list_, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.delete( + "list_id", + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.with_raw_response.delete( + "list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.lists.with_streaming_response.delete( + "list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert list_ is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_restore(self, async_client: AsyncCourier) -> None: + list_ = await async_client.lists.restore( + "list_id", + ) + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_restore(self, async_client: AsyncCourier) -> None: + response = await async_client.lists.with_raw_response.restore( + "list_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + list_ = await response.parse() + assert list_ is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_restore(self, async_client: AsyncCourier) -> None: + async with async_client.lists.with_streaming_response.restore( + "list_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + list_ = await response.parse() + assert list_ is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_restore(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `list_id` but received ''"): + await async_client.lists.with_raw_response.restore( + "", + ) diff --git a/tests/api_resources/test_messages.py b/tests/api_resources/test_messages.py new file mode 100644 index 00000000..f65fabaf --- /dev/null +++ b/tests/api_resources/test_messages.py @@ -0,0 +1,567 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + MessageDetails, + MessageListResponse, + MessageResendResponse, + MessageContentResponse, + MessageHistoryResponse, + MessageRetrieveResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestMessages: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + message = client.messages.retrieve( + "message_id", + ) + assert_matches_type(MessageRetrieveResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.messages.with_raw_response.retrieve( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageRetrieveResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.messages.with_streaming_response.retrieve( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageRetrieveResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.messages.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + message = client.messages.list() + assert_matches_type(MessageListResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + message = client.messages.list( + archived=True, + cursor="cursor", + enqueued_after="enqueued_after", + event="event", + list="list", + message_id="messageId", + notification="notification", + provider=["string"], + recipient="recipient", + status=["string"], + tag=["string"], + tags="tags", + tenant_id="tenant_id", + trace_id="traceId", + ) + assert_matches_type(MessageListResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.messages.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageListResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.messages.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageListResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_cancel(self, client: Courier) -> None: + message = client.messages.cancel( + "message_id", + ) + assert_matches_type(MessageDetails, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_cancel(self, client: Courier) -> None: + response = client.messages.with_raw_response.cancel( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageDetails, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_cancel(self, client: Courier) -> None: + with client.messages.with_streaming_response.cancel( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageDetails, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_cancel(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.messages.with_raw_response.cancel( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_content(self, client: Courier) -> None: + message = client.messages.content( + "message_id", + ) + assert_matches_type(MessageContentResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_content(self, client: Courier) -> None: + response = client.messages.with_raw_response.content( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageContentResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_content(self, client: Courier) -> None: + with client.messages.with_streaming_response.content( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageContentResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.messages.with_raw_response.content( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_history(self, client: Courier) -> None: + message = client.messages.history( + message_id="message_id", + ) + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_history_with_all_params(self, client: Courier) -> None: + message = client.messages.history( + message_id="message_id", + type="type", + ) + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_history(self, client: Courier) -> None: + response = client.messages.with_raw_response.history( + message_id="message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_history(self, client: Courier) -> None: + with client.messages.with_streaming_response.history( + message_id="message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_history(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.messages.with_raw_response.history( + message_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_resend(self, client: Courier) -> None: + message = client.messages.resend( + "message_id", + ) + assert_matches_type(MessageResendResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_resend(self, client: Courier) -> None: + response = client.messages.with_raw_response.resend( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageResendResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_resend(self, client: Courier) -> None: + with client.messages.with_streaming_response.resend( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageResendResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_resend(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.messages.with_raw_response.resend( + "", + ) + + +class TestAsyncMessages: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.retrieve( + "message_id", + ) + assert_matches_type(MessageRetrieveResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.messages.with_raw_response.retrieve( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = await response.parse() + assert_matches_type(MessageRetrieveResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.messages.with_streaming_response.retrieve( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageRetrieveResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await async_client.messages.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.list() + assert_matches_type(MessageListResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.list( + archived=True, + cursor="cursor", + enqueued_after="enqueued_after", + event="event", + list="list", + message_id="messageId", + notification="notification", + provider=["string"], + recipient="recipient", + status=["string"], + tag=["string"], + tags="tags", + tenant_id="tenant_id", + trace_id="traceId", + ) + assert_matches_type(MessageListResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.messages.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = await response.parse() + assert_matches_type(MessageListResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.messages.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageListResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_cancel(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.cancel( + "message_id", + ) + assert_matches_type(MessageDetails, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_cancel(self, async_client: AsyncCourier) -> None: + response = await async_client.messages.with_raw_response.cancel( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = await response.parse() + assert_matches_type(MessageDetails, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_cancel(self, async_client: AsyncCourier) -> None: + async with async_client.messages.with_streaming_response.cancel( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageDetails, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_cancel(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await async_client.messages.with_raw_response.cancel( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_content(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.content( + "message_id", + ) + assert_matches_type(MessageContentResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_content(self, async_client: AsyncCourier) -> None: + response = await async_client.messages.with_raw_response.content( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = await response.parse() + assert_matches_type(MessageContentResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_content(self, async_client: AsyncCourier) -> None: + async with async_client.messages.with_streaming_response.content( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageContentResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await async_client.messages.with_raw_response.content( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_history(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.history( + message_id="message_id", + ) + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_history_with_all_params(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.history( + message_id="message_id", + type="type", + ) + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_history(self, async_client: AsyncCourier) -> None: + response = await async_client.messages.with_raw_response.history( + message_id="message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = await response.parse() + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_history(self, async_client: AsyncCourier) -> None: + async with async_client.messages.with_streaming_response.history( + message_id="message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageHistoryResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_history(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await async_client.messages.with_raw_response.history( + message_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_resend(self, async_client: AsyncCourier) -> None: + message = await async_client.messages.resend( + "message_id", + ) + assert_matches_type(MessageResendResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_resend(self, async_client: AsyncCourier) -> None: + response = await async_client.messages.with_raw_response.resend( + "message_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = await response.parse() + assert_matches_type(MessageResendResponse, message, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_resend(self, async_client: AsyncCourier) -> None: + async with async_client.messages.with_streaming_response.resend( + "message_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageResendResponse, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_resend(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await async_client.messages.with_raw_response.resend( + "", + ) diff --git a/tests/api_resources/test_notifications.py b/tests/api_resources/test_notifications.py new file mode 100644 index 00000000..8e40d813 --- /dev/null +++ b/tests/api_resources/test_notifications.py @@ -0,0 +1,1474 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + NotificationListResponse, + NotificationTemplateResponse, + NotificationContentMutationResponse, + NotificationRetrieveContentResponse, + NotificationTemplateVersionListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestNotifications: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + notification = client.notifications.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + }, + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + notification = client.notifications.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + "alias": "welcome", + }, + state="DRAFT", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.notifications.with_raw_response.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.notifications.with_streaming_response.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + notification = client.notifications.retrieve( + id="id", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_with_all_params(self, client: Courier) -> None: + notification = client.notifications.retrieve( + id="id", + version="version", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.notifications.with_raw_response.retrieve( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.notifications.with_streaming_response.retrieve( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.retrieve( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + notification = client.notifications.list() + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + notification = client.notifications.list( + cursor="cursor", + event_id="event_id", + notes=True, + ) + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.notifications.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.notifications.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + notification = client.notifications.archive( + "id", + ) + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.notifications.with_raw_response.archive( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.notifications.with_streaming_response.archive( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert notification is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_duplicate(self, client: Courier) -> None: + notification = client.notifications.duplicate( + "id", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_duplicate(self, client: Courier) -> None: + response = client.notifications.with_raw_response.duplicate( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_duplicate(self, client: Courier) -> None: + with client.notifications.with_streaming_response.duplicate( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_duplicate(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.duplicate( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_versions(self, client: Courier) -> None: + notification = client.notifications.list_versions( + id="id", + ) + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_versions_with_all_params(self, client: Courier) -> None: + notification = client.notifications.list_versions( + id="id", + cursor="cursor", + limit=10, + ) + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_versions(self, client: Courier) -> None: + response = client.notifications.with_raw_response.list_versions( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_versions(self, client: Courier) -> None: + with client.notifications.with_streaming_response.list_versions( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_versions(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.list_versions( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish(self, client: Courier) -> None: + notification = client.notifications.publish( + id="id", + ) + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish_with_all_params(self, client: Courier) -> None: + notification = client.notifications.publish( + id="id", + version="v321669910225", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_publish(self, client: Courier) -> None: + response = client.notifications.with_raw_response.publish( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_publish(self, client: Courier) -> None: + with client.notifications.with_streaming_response.publish( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert notification is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_publish(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.publish( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_content(self, client: Courier) -> None: + notification = client.notifications.put_content( + id="id", + content={"elements": [{}]}, + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_content_with_all_params(self, client: Courier) -> None: + notification = client.notifications.put_content( + id="id", + content={ + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_put_content(self, client: Courier) -> None: + response = client.notifications.with_raw_response.put_content( + id="id", + content={"elements": [{}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_put_content(self, client: Courier) -> None: + with client.notifications.with_streaming_response.put_content( + id="id", + content={"elements": [{}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_put_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.put_content( + id="", + content={"elements": [{}]}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_element(self, client: Courier) -> None: + notification = client.notifications.put_element( + element_id="elementId", + id="id", + type="text", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_element_with_all_params(self, client: Courier) -> None: + notification = client.notifications.put_element( + element_id="elementId", + id="id", + type="text", + channels=["string"], + data={"content": "bar"}, + if_="if", + loop="loop", + ref="ref", + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_put_element(self, client: Courier) -> None: + response = client.notifications.with_raw_response.put_element( + element_id="elementId", + id="id", + type="text", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_put_element(self, client: Courier) -> None: + with client.notifications.with_streaming_response.put_element( + element_id="elementId", + id="id", + type="text", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_put_element(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.put_element( + element_id="elementId", + id="", + type="text", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `element_id` but received ''"): + client.notifications.with_raw_response.put_element( + element_id="", + id="id", + type="text", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_locale(self, client: Courier) -> None: + notification = client.notifications.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_put_locale_with_all_params(self, client: Courier) -> None: + notification = client.notifications.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_put_locale(self, client: Courier) -> None: + response = client.notifications.with_raw_response.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_put_locale(self, client: Courier) -> None: + with client.notifications.with_streaming_response.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_put_locale(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.put_locale( + locale_id="localeId", + id="", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale_id` but received ''"): + client.notifications.with_raw_response.put_locale( + locale_id="", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + notification = client.notifications.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + notification = client.notifications.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + "alias": "alias", + }, + state="PUBLISHED", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.notifications.with_raw_response.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.notifications.with_streaming_response.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.replace( + id="", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_content(self, client: Courier) -> None: + notification = client.notifications.retrieve_content( + id="id", + ) + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_content_with_all_params(self, client: Courier) -> None: + notification = client.notifications.retrieve_content( + id="id", + version="version", + ) + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve_content(self, client: Courier) -> None: + response = client.notifications.with_raw_response.retrieve_content( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = response.parse() + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve_content(self, client: Courier) -> None: + with client.notifications.with_streaming_response.retrieve_content( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = response.parse() + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve_content(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.notifications.with_raw_response.retrieve_content( + id="", + ) + + +class TestAsyncNotifications: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + }, + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + "alias": "welcome", + }, + state="DRAFT", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.create( + notification={ + "brand": {"id": "bnd_01kx4mrd0pfzw8wt7pn7p2fzag"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Welcome Email", + "routing": {"strategy_id": "rs_01kx4h2jdafq8bk9amzvy6hbv0"}, + "subscription": {"topic_id": "pt_01kx4h2jdafq8bk9a26x0kvd1t"}, + "tags": ["onboarding", "welcome"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.retrieve( + id="id", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.retrieve( + id="id", + version="version", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.retrieve( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.retrieve( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.retrieve( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.list() + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.list( + cursor="cursor", + event_id="event_id", + notes=True, + ) + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationListResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.archive( + "id", + ) + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.archive( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.archive( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert notification is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_duplicate(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.duplicate( + "id", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_duplicate(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.duplicate( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_duplicate(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.duplicate( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_duplicate(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.duplicate( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_versions(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.list_versions( + id="id", + ) + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_versions_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.list_versions( + id="id", + cursor="cursor", + limit=10, + ) + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_versions(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.list_versions( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_versions(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.list_versions( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationTemplateVersionListResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_versions(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.list_versions( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.publish( + id="id", + ) + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.publish( + id="id", + version="v321669910225", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_publish(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.publish( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert notification is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_publish(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.publish( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert notification is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_publish(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.publish( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_content(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.put_content( + id="id", + content={"elements": [{}]}, + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_content_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.put_content( + id="id", + content={ + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_put_content(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.put_content( + id="id", + content={"elements": [{}]}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_put_content(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.put_content( + id="id", + content={"elements": [{}]}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_put_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.put_content( + id="", + content={"elements": [{}]}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_element(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.put_element( + element_id="elementId", + id="id", + type="text", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_element_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.put_element( + element_id="elementId", + id="id", + type="text", + channels=["string"], + data={"content": "bar"}, + if_="if", + loop="loop", + ref="ref", + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_put_element(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.put_element( + element_id="elementId", + id="id", + type="text", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_put_element(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.put_element( + element_id="elementId", + id="id", + type="text", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_put_element(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.put_element( + element_id="elementId", + id="", + type="text", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `element_id` but received ''"): + await async_client.notifications.with_raw_response.put_element( + element_id="", + id="id", + type="text", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_locale(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_put_locale_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + state="DRAFT", + ) + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_put_locale(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_put_locale(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.put_locale( + locale_id="localeId", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationContentMutationResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_put_locale(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.put_locale( + locale_id="localeId", + id="", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale_id` but received ''"): + await async_client.notifications.with_raw_response.put_locale( + locale_id="", + id="id", + elements=[{"id": "elem_1"}, {"id": "elem_2"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{"type": "channel"}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + "alias": "alias", + }, + state="PUBLISHED", + ) + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.replace( + id="id", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationTemplateResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.replace( + id="", + notification={ + "brand": {"id": "id"}, + "content": { + "elements": [{}], + "version": "2022-01-01", + }, + "name": "Updated Name", + "routing": {"strategy_id": "strategy_id"}, + "subscription": {"topic_id": "topic_id"}, + "tags": ["updated"], + }, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_content(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.retrieve_content( + id="id", + ) + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_content_with_all_params(self, async_client: AsyncCourier) -> None: + notification = await async_client.notifications.retrieve_content( + id="id", + version="version", + ) + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve_content(self, async_client: AsyncCourier) -> None: + response = await async_client.notifications.with_raw_response.retrieve_content( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + notification = await response.parse() + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve_content(self, async_client: AsyncCourier) -> None: + async with async_client.notifications.with_streaming_response.retrieve_content( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + notification = await response.parse() + assert_matches_type(NotificationRetrieveContentResponse, notification, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve_content(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.notifications.with_raw_response.retrieve_content( + id="", + ) diff --git a/tests/api_resources/test_profiles.py b/tests/api_resources/test_profiles.py new file mode 100644 index 00000000..b90cb5f0 --- /dev/null +++ b/tests/api_resources/test_profiles.py @@ -0,0 +1,542 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + ProfileCreateResponse, + ProfileReplaceResponse, + ProfileRetrieveResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestProfiles: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + profile = client.profiles.create( + user_id="user_id", + profile={"foo": "bar"}, + ) + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + profile = client.profiles.create( + user_id="user_id", + profile={"foo": "bar"}, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.profiles.with_raw_response.create( + user_id="user_id", + profile={"foo": "bar"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = response.parse() + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.profiles.with_streaming_response.create( + user_id="user_id", + profile={"foo": "bar"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = response.parse() + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_create(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.with_raw_response.create( + user_id="", + profile={"foo": "bar"}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + profile = client.profiles.retrieve( + "user_id", + ) + assert_matches_type(ProfileRetrieveResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.profiles.with_raw_response.retrieve( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = response.parse() + assert_matches_type(ProfileRetrieveResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.profiles.with_streaming_response.retrieve( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = response.parse() + assert_matches_type(ProfileRetrieveResponse, profile, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + profile = client.profiles.update( + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.profiles.with_raw_response.update( + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = response.parse() + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.profiles.with_streaming_response.update( + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = response.parse() + assert profile is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.with_raw_response.update( + user_id="", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + profile = client.profiles.delete( + "user_id", + ) + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.profiles.with_raw_response.delete( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = response.parse() + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.profiles.with_streaming_response.delete( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = response.parse() + assert profile is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + profile = client.profiles.replace( + user_id="user_id", + profile={"foo": "bar"}, + ) + assert_matches_type(ProfileReplaceResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.profiles.with_raw_response.replace( + user_id="user_id", + profile={"foo": "bar"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = response.parse() + assert_matches_type(ProfileReplaceResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.profiles.with_streaming_response.replace( + user_id="user_id", + profile={"foo": "bar"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = response.parse() + assert_matches_type(ProfileReplaceResponse, profile, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.profiles.with_raw_response.replace( + user_id="", + profile={"foo": "bar"}, + ) + + +class TestAsyncProfiles: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + profile = await async_client.profiles.create( + user_id="user_id", + profile={"foo": "bar"}, + ) + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + profile = await async_client.profiles.create( + user_id="user_id", + profile={"foo": "bar"}, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.with_raw_response.create( + user_id="user_id", + profile={"foo": "bar"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = await response.parse() + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.with_streaming_response.create( + user_id="user_id", + profile={"foo": "bar"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = await response.parse() + assert_matches_type(ProfileCreateResponse, profile, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_create(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.with_raw_response.create( + user_id="", + profile={"foo": "bar"}, + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + profile = await async_client.profiles.retrieve( + "user_id", + ) + assert_matches_type(ProfileRetrieveResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.with_raw_response.retrieve( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = await response.parse() + assert_matches_type(ProfileRetrieveResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.with_streaming_response.retrieve( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = await response.parse() + assert_matches_type(ProfileRetrieveResponse, profile, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + profile = await async_client.profiles.update( + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.with_raw_response.update( + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = await response.parse() + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.with_streaming_response.update( + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = await response.parse() + assert profile is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.with_raw_response.update( + user_id="", + patch=[ + { + "op": "op", + "path": "path", + "value": "value", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + profile = await async_client.profiles.delete( + "user_id", + ) + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.with_raw_response.delete( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = await response.parse() + assert profile is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.with_streaming_response.delete( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = await response.parse() + assert profile is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + profile = await async_client.profiles.replace( + user_id="user_id", + profile={"foo": "bar"}, + ) + assert_matches_type(ProfileReplaceResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.profiles.with_raw_response.replace( + user_id="user_id", + profile={"foo": "bar"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + profile = await response.parse() + assert_matches_type(ProfileReplaceResponse, profile, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.profiles.with_streaming_response.replace( + user_id="user_id", + profile={"foo": "bar"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + profile = await response.parse() + assert_matches_type(ProfileReplaceResponse, profile, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.profiles.with_raw_response.replace( + user_id="", + profile={"foo": "bar"}, + ) diff --git a/tests/api_resources/test_providers.py b/tests/api_resources/test_providers.py new file mode 100644 index 00000000..10e8d743 --- /dev/null +++ b/tests/api_resources/test_providers.py @@ -0,0 +1,477 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + Provider, + ProviderListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestProviders: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + provider = client.providers.create( + provider="provider", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + provider = client.providers.create( + provider="provider", + alias="alias", + settings={"foo": "bar"}, + title="title", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.providers.with_raw_response.create( + provider="provider", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.providers.with_streaming_response.create( + provider="provider", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + provider = client.providers.retrieve( + "id", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.providers.with_raw_response.retrieve( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.providers.with_streaming_response.retrieve( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.providers.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + provider = client.providers.update( + id="id", + provider="provider", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_with_all_params(self, client: Courier) -> None: + provider = client.providers.update( + id="id", + provider="provider", + alias="alias", + settings={"foo": "bar"}, + title="title", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.providers.with_raw_response.update( + id="id", + provider="provider", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.providers.with_streaming_response.update( + id="id", + provider="provider", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.providers.with_raw_response.update( + id="", + provider="provider", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + provider = client.providers.list() + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + provider = client.providers.list( + cursor="cursor", + ) + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.providers.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = response.parse() + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.providers.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = response.parse() + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + provider = client.providers.delete( + "id", + ) + assert provider is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.providers.with_raw_response.delete( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = response.parse() + assert provider is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.providers.with_streaming_response.delete( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = response.parse() + assert provider is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.providers.with_raw_response.delete( + "", + ) + + +class TestAsyncProviders: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.create( + provider="provider", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.create( + provider="provider", + alias="alias", + settings={"foo": "bar"}, + title="title", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.providers.with_raw_response.create( + provider="provider", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = await response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.providers.with_streaming_response.create( + provider="provider", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = await response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.retrieve( + "id", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.providers.with_raw_response.retrieve( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = await response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.providers.with_streaming_response.retrieve( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = await response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.providers.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.update( + id="id", + provider="provider", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.update( + id="id", + provider="provider", + alias="alias", + settings={"foo": "bar"}, + title="title", + ) + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.providers.with_raw_response.update( + id="id", + provider="provider", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = await response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.providers.with_streaming_response.update( + id="id", + provider="provider", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = await response.parse() + assert_matches_type(Provider, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.providers.with_raw_response.update( + id="", + provider="provider", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.list() + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.list( + cursor="cursor", + ) + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.providers.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = await response.parse() + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.providers.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = await response.parse() + assert_matches_type(ProviderListResponse, provider, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + provider = await async_client.providers.delete( + "id", + ) + assert provider is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.providers.with_raw_response.delete( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + provider = await response.parse() + assert provider is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.providers.with_streaming_response.delete( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + provider = await response.parse() + assert provider is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.providers.with_raw_response.delete( + "", + ) diff --git a/tests/api_resources/test_requests.py b/tests/api_resources/test_requests.py new file mode 100644 index 00000000..b813d130 --- /dev/null +++ b/tests/api_resources/test_requests.py @@ -0,0 +1,106 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestRequests: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + request = client.requests.archive( + "request_id", + ) + assert request is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.requests.with_raw_response.archive( + "request_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + request = response.parse() + assert request is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.requests.with_streaming_response.archive( + "request_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + request = response.parse() + assert request is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `request_id` but received ''"): + client.requests.with_raw_response.archive( + "", + ) + + +class TestAsyncRequests: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + request = await async_client.requests.archive( + "request_id", + ) + assert request is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.requests.with_raw_response.archive( + "request_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + request = await response.parse() + assert request is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.requests.with_streaming_response.archive( + "request_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + request = await response.parse() + assert request is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `request_id` but received ''"): + await async_client.requests.with_raw_response.archive( + "", + ) diff --git a/tests/api_resources/test_routing_strategies.py b/tests/api_resources/test_routing_strategies.py new file mode 100644 index 00000000..2a19e86e --- /dev/null +++ b/tests/api_resources/test_routing_strategies.py @@ -0,0 +1,804 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + RoutingStrategyGetResponse, + RoutingStrategyListResponse, + AssociatedNotificationListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestRoutingStrategies: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + channels={ + "email": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["sendgrid", "ses"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + description="Routes email through sendgrid with SES failover", + providers={ + "sendgrid": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {}, + "timeouts": 0, + } + }, + tags=["production", "email"], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.routing_strategies.with_raw_response.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.routing_strategies.with_streaming_response.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.retrieve( + "id", + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.routing_strategies.with_raw_response.retrieve( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.routing_strategies.with_streaming_response.retrieve( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.routing_strategies.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.list() + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.list( + cursor="cursor", + limit=1, + ) + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.routing_strategies.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.routing_strategies.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.archive( + "id", + ) + assert routing_strategy is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.routing_strategies.with_raw_response.archive( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = response.parse() + assert routing_strategy is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.routing_strategies.with_streaming_response.archive( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = response.parse() + assert routing_strategy is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.routing_strategies.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_notifications(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.list_notifications( + id="id", + ) + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_notifications_with_all_params(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.list_notifications( + id="id", + cursor="cursor", + limit=1, + ) + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_notifications(self, client: Courier) -> None: + response = client.routing_strategies.with_raw_response.list_notifications( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = response.parse() + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_notifications(self, client: Courier) -> None: + with client.routing_strategies.with_streaming_response.list_notifications( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = response.parse() + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_notifications(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.routing_strategies.with_raw_response.list_notifications( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + routing_strategy = client.routing_strategies.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + channels={ + "email": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["ses", "sendgrid"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + description="Updated routing with SES primary", + providers={ + "ses": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {}, + "timeouts": 0, + } + }, + tags=["production", "email", "v2"], + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.routing_strategies.with_raw_response.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.routing_strategies.with_streaming_response.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + client.routing_strategies.with_raw_response.replace( + id="", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + + +class TestAsyncRoutingStrategies: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + channels={ + "email": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["sendgrid", "ses"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + description="Routes email through sendgrid with SES failover", + providers={ + "sendgrid": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {}, + "timeouts": 0, + } + }, + tags=["production", "email"], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.routing_strategies.with_raw_response.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.routing_strategies.with_streaming_response.create( + name="Email via SendGrid", + routing={ + "channels": ["email"], + "method": "single", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.retrieve( + "id", + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.routing_strategies.with_raw_response.retrieve( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.routing_strategies.with_streaming_response.retrieve( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.routing_strategies.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.list() + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.list( + cursor="cursor", + limit=1, + ) + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.routing_strategies.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.routing_strategies.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyListResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.archive( + "id", + ) + assert routing_strategy is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.routing_strategies.with_raw_response.archive( + "id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = await response.parse() + assert routing_strategy is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.routing_strategies.with_streaming_response.archive( + "id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = await response.parse() + assert routing_strategy is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.routing_strategies.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_notifications(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.list_notifications( + id="id", + ) + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_notifications_with_all_params(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.list_notifications( + id="id", + cursor="cursor", + limit=1, + ) + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_notifications(self, async_client: AsyncCourier) -> None: + response = await async_client.routing_strategies.with_raw_response.list_notifications( + id="id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = await response.parse() + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_notifications(self, async_client: AsyncCourier) -> None: + async with async_client.routing_strategies.with_streaming_response.list_notifications( + id="id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = await response.parse() + assert_matches_type(AssociatedNotificationListResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_notifications(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.routing_strategies.with_raw_response.list_notifications( + id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + routing_strategy = await async_client.routing_strategies.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + channels={ + "email": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["ses", "sendgrid"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + description="Updated routing with SES primary", + providers={ + "ses": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {}, + "timeouts": 0, + } + }, + tags=["production", "email", "v2"], + ) + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.routing_strategies.with_raw_response.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.routing_strategies.with_streaming_response.replace( + id="id", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + routing_strategy = await response.parse() + assert_matches_type(RoutingStrategyGetResponse, routing_strategy, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `id` but received ''"): + await async_client.routing_strategies.with_raw_response.replace( + id="", + name="Email via SendGrid v2", + routing={ + "channels": ["email"], + "method": "single", + }, + ) diff --git a/tests/api_resources/test_send.py b/tests/api_resources/test_send.py new file mode 100644 index 00000000..7f92c54c --- /dev/null +++ b/tests/api_resources/test_send.py @@ -0,0 +1,352 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import SendMessageResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestSend: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_message(self, client: Courier) -> None: + send = client.send.message( + message={}, + ) + assert_matches_type(SendMessageResponse, send, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_message_with_all_params(self, client: Courier) -> None: + send = client.send.message( + message={ + "brand_id": "brand_id", + "channels": { + "foo": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["string"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + "content": { + "body": "body", + "title": "title", + }, + "context": {"tenant_id": "tenant_id"}, + "data": {"foo": "bar"}, + "delay": { + "duration": 0, + "timezone": "timezone", + "until": "until", + }, + "expiry": { + "expires_in": "string", + "expires_at": "expires_at", + }, + "metadata": { + "event": "event", + "tags": ["string"], + "trace_id": "trace_id", + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + }, + }, + "preferences": {"subscription_topic_id": "subscription_topic_id"}, + "providers": { + "foo": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "timeouts": 0, + } + }, + "routing": { + "channels": ["string"], + "method": "all", + }, + "template": "template_id", + "timeout": { + "channel": {"foo": 0}, + "criteria": "no-escalation", + "escalation": 0, + "message": 0, + "provider": {"foo": 0}, + }, + "to": { + "account_id": "account_id", + "context": {"tenant_id": "tenant_id"}, + "data": {"foo": "bar"}, + "email": "email", + "list_id": "list_id", + "locale": "locale", + "phone_number": "phone_number", + "preferences": { + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + "source": "subscription", + } + }, + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + "source": "subscription", + } + }, + "template_id": "templateId", + }, + "tenant_id": "tenant_id", + "user_id": "user_id", + }, + }, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(SendMessageResponse, send, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_message(self, client: Courier) -> None: + response = client.send.with_raw_response.message( + message={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + send = response.parse() + assert_matches_type(SendMessageResponse, send, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_message(self, client: Courier) -> None: + with client.send.with_streaming_response.message( + message={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + send = response.parse() + assert_matches_type(SendMessageResponse, send, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncSend: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_message(self, async_client: AsyncCourier) -> None: + send = await async_client.send.message( + message={}, + ) + assert_matches_type(SendMessageResponse, send, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_message_with_all_params(self, async_client: AsyncCourier) -> None: + send = await async_client.send.message( + message={ + "brand_id": "brand_id", + "channels": { + "foo": { + "brand_id": "brand_id", + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "providers": ["string"], + "routing_method": "all", + "timeouts": { + "channel": 0, + "provider": 0, + }, + } + }, + "content": { + "body": "body", + "title": "title", + }, + "context": {"tenant_id": "tenant_id"}, + "data": {"foo": "bar"}, + "delay": { + "duration": 0, + "timezone": "timezone", + "until": "until", + }, + "expiry": { + "expires_in": "string", + "expires_at": "expires_at", + }, + "metadata": { + "event": "event", + "tags": ["string"], + "trace_id": "trace_id", + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + }, + }, + "preferences": {"subscription_topic_id": "subscription_topic_id"}, + "providers": { + "foo": { + "if": "if", + "metadata": { + "utm": { + "campaign": "campaign", + "content": "content", + "medium": "medium", + "source": "source", + "term": "term", + } + }, + "override": {"foo": "bar"}, + "timeouts": 0, + } + }, + "routing": { + "channels": ["string"], + "method": "all", + }, + "template": "template_id", + "timeout": { + "channel": {"foo": 0}, + "criteria": "no-escalation", + "escalation": 0, + "message": 0, + "provider": {"foo": 0}, + }, + "to": { + "account_id": "account_id", + "context": {"tenant_id": "tenant_id"}, + "data": {"foo": "bar"}, + "email": "email", + "list_id": "list_id", + "locale": "locale", + "phone_number": "phone_number", + "preferences": { + "notifications": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + "source": "subscription", + } + }, + "categories": { + "foo": { + "status": "OPTED_IN", + "channel_preferences": [{"channel": "direct_message"}], + "rules": [ + { + "until": "until", + "start": "start", + } + ], + "source": "subscription", + } + }, + "template_id": "templateId", + }, + "tenant_id": "tenant_id", + "user_id": "user_id", + }, + }, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(SendMessageResponse, send, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_message(self, async_client: AsyncCourier) -> None: + response = await async_client.send.with_raw_response.message( + message={}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + send = await response.parse() + assert_matches_type(SendMessageResponse, send, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_message(self, async_client: AsyncCourier) -> None: + async with async_client.send.with_streaming_response.message( + message={}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + send = await response.parse() + assert_matches_type(SendMessageResponse, send, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_tenants.py b/tests/api_resources/test_tenants.py new file mode 100644 index 00000000..52e3494c --- /dev/null +++ b/tests/api_resources/test_tenants.py @@ -0,0 +1,514 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + Tenant, + TenantListResponse, + TenantListUsersResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTenants: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + tenant = client.tenants.retrieve( + "tenant_id", + ) + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.tenants.with_raw_response.retrieve( + "tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.tenants.with_streaming_response.retrieve( + "tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + tenant = client.tenants.update( + tenant_id="tenant_id", + name="name", + ) + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_with_all_params(self, client: Courier) -> None: + tenant = client.tenants.update( + tenant_id="tenant_id", + name="name", + brand_id="brand_id", + default_preferences={ + "items": [ + { + "status": "OPTED_OUT", + "custom_routing": ["direct_message"], + "has_custom_routing": True, + "id": "id", + } + ] + }, + parent_tenant_id="parent_tenant_id", + properties={"foo": "bar"}, + user_profile={"foo": "bar"}, + ) + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.tenants.with_raw_response.update( + tenant_id="tenant_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.tenants.with_streaming_response.update( + tenant_id="tenant_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.with_raw_response.update( + tenant_id="", + name="name", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + tenant = client.tenants.list() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + tenant = client.tenants.list( + cursor="cursor", + limit=0, + parent_tenant_id="parent_tenant_id", + ) + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.tenants.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.tenants.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + tenant = client.tenants.delete( + "tenant_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.tenants.with_raw_response.delete( + "tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.tenants.with_streaming_response.delete( + "tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_users(self, client: Courier) -> None: + tenant = client.tenants.list_users( + tenant_id="tenant_id", + ) + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_users_with_all_params(self, client: Courier) -> None: + tenant = client.tenants.list_users( + tenant_id="tenant_id", + cursor="cursor", + limit=0, + ) + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list_users(self, client: Courier) -> None: + response = client.tenants.with_raw_response.list_users( + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list_users(self, client: Courier) -> None: + with client.tenants.with_streaming_response.list_users( + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list_users(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.tenants.with_raw_response.list_users( + tenant_id="", + ) + + +class TestAsyncTenants: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.retrieve( + "tenant_id", + ) + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.with_raw_response.retrieve( + "tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.with_streaming_response.retrieve( + "tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.update( + tenant_id="tenant_id", + name="name", + ) + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.update( + tenant_id="tenant_id", + name="name", + brand_id="brand_id", + default_preferences={ + "items": [ + { + "status": "OPTED_OUT", + "custom_routing": ["direct_message"], + "has_custom_routing": True, + "id": "id", + } + ] + }, + parent_tenant_id="parent_tenant_id", + properties={"foo": "bar"}, + user_profile={"foo": "bar"}, + ) + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.with_raw_response.update( + tenant_id="tenant_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.with_streaming_response.update( + tenant_id="tenant_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert_matches_type(Tenant, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.with_raw_response.update( + tenant_id="", + name="name", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.list() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.list( + cursor="cursor", + limit=0, + parent_tenant_id="parent_tenant_id", + ) + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.delete( + "tenant_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.with_raw_response.delete( + "tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.with_streaming_response.delete( + "tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.with_raw_response.delete( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_users(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.list_users( + tenant_id="tenant_id", + ) + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_users_with_all_params(self, async_client: AsyncCourier) -> None: + tenant = await async_client.tenants.list_users( + tenant_id="tenant_id", + cursor="cursor", + limit=0, + ) + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list_users(self, async_client: AsyncCourier) -> None: + response = await async_client.tenants.with_raw_response.list_users( + tenant_id="tenant_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list_users(self, async_client: AsyncCourier) -> None: + async with async_client.tenants.with_streaming_response.list_users( + tenant_id="tenant_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert_matches_type(TenantListUsersResponse, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list_users(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.tenants.with_raw_response.list_users( + tenant_id="", + ) diff --git a/tests/api_resources/test_translations.py b/tests/api_resources/test_translations.py new file mode 100644 index 00000000..b53eb7f7 --- /dev/null +++ b/tests/api_resources/test_translations.py @@ -0,0 +1,241 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTranslations: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + translation = client.translations.retrieve( + locale="locale", + domain="domain", + ) + assert_matches_type(str, translation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.translations.with_raw_response.retrieve( + locale="locale", + domain="domain", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + translation = response.parse() + assert_matches_type(str, translation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.translations.with_streaming_response.retrieve( + locale="locale", + domain="domain", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + translation = response.parse() + assert_matches_type(str, translation, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `domain` but received ''"): + client.translations.with_raw_response.retrieve( + locale="locale", + domain="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale` but received ''"): + client.translations.with_raw_response.retrieve( + locale="", + domain="domain", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + translation = client.translations.update( + locale="locale", + domain="domain", + body="body", + ) + assert translation is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.translations.with_raw_response.update( + locale="locale", + domain="domain", + body="body", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + translation = response.parse() + assert translation is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.translations.with_streaming_response.update( + locale="locale", + domain="domain", + body="body", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + translation = response.parse() + assert translation is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `domain` but received ''"): + client.translations.with_raw_response.update( + locale="locale", + domain="", + body="body", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale` but received ''"): + client.translations.with_raw_response.update( + locale="", + domain="domain", + body="body", + ) + + +class TestAsyncTranslations: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + translation = await async_client.translations.retrieve( + locale="locale", + domain="domain", + ) + assert_matches_type(str, translation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.translations.with_raw_response.retrieve( + locale="locale", + domain="domain", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + translation = await response.parse() + assert_matches_type(str, translation, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.translations.with_streaming_response.retrieve( + locale="locale", + domain="domain", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + translation = await response.parse() + assert_matches_type(str, translation, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `domain` but received ''"): + await async_client.translations.with_raw_response.retrieve( + locale="locale", + domain="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale` but received ''"): + await async_client.translations.with_raw_response.retrieve( + locale="", + domain="domain", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + translation = await async_client.translations.update( + locale="locale", + domain="domain", + body="body", + ) + assert translation is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.translations.with_raw_response.update( + locale="locale", + domain="domain", + body="body", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + translation = await response.parse() + assert translation is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.translations.with_streaming_response.update( + locale="locale", + domain="domain", + body="body", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + translation = await response.parse() + assert translation is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `domain` but received ''"): + await async_client.translations.with_raw_response.update( + locale="locale", + domain="", + body="body", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `locale` but received ''"): + await async_client.translations.with_raw_response.update( + locale="", + domain="domain", + body="body", + ) diff --git a/tests/api_resources/test_workspace_preferences.py b/tests/api_resources/test_workspace_preferences.py new file mode 100644 index 00000000..b3802b5e --- /dev/null +++ b/tests/api_resources/test_workspace_preferences.py @@ -0,0 +1,542 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import ( + PublishPreferencesResponse, + WorkspacePreferenceGetResponse, + WorkspacePreferenceListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestWorkspacePreferences: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.create( + name="Account Notifications", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.create( + name="Account Notifications", + description="description", + has_custom_routing=True, + routing_options=["direct_message"], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.workspace_preferences.with_raw_response.create( + name="Account Notifications", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.workspace_preferences.with_streaming_response.create( + name="Account Notifications", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.retrieve( + "section_id", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.workspace_preferences.with_raw_response.retrieve( + "section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.workspace_preferences.with_streaming_response.retrieve( + "section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.list() + assert_matches_type(WorkspacePreferenceListResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.workspace_preferences.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceListResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.workspace_preferences.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceListResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.archive( + "section_id", + ) + assert workspace_preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.workspace_preferences.with_raw_response.archive( + "section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = response.parse() + assert workspace_preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.workspace_preferences.with_streaming_response.archive( + "section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = response.parse() + assert workspace_preference is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.publish() + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_publish_with_all_params(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.publish( + brand_id="brand_id", + description="description", + heading="heading", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_publish(self, client: Courier) -> None: + response = client.workspace_preferences.with_raw_response.publish() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = response.parse() + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_publish(self, client: Courier) -> None: + with client.workspace_preferences.with_streaming_response.publish() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = response.parse() + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.replace( + section_id="section_id", + name="name", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + workspace_preference = client.workspace_preferences.replace( + section_id="section_id", + name="name", + description="description", + has_custom_routing=True, + routing_options=["direct_message"], + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.workspace_preferences.with_raw_response.replace( + section_id="section_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.workspace_preferences.with_streaming_response.replace( + section_id="section_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.with_raw_response.replace( + section_id="", + name="name", + ) + + +class TestAsyncWorkspacePreferences: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.create( + name="Account Notifications", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.create( + name="Account Notifications", + description="description", + has_custom_routing=True, + routing_options=["direct_message"], + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.with_raw_response.create( + name="Account Notifications", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.with_streaming_response.create( + name="Account Notifications", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.retrieve( + "section_id", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.with_raw_response.retrieve( + "section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.with_streaming_response.retrieve( + "section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.with_raw_response.retrieve( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.list() + assert_matches_type(WorkspacePreferenceListResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceListResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceListResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.archive( + "section_id", + ) + assert workspace_preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.with_raw_response.archive( + "section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = await response.parse() + assert workspace_preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.with_streaming_response.archive( + "section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = await response.parse() + assert workspace_preference is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.with_raw_response.archive( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.publish() + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_publish_with_all_params(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.publish( + brand_id="brand_id", + description="description", + heading="heading", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_publish(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.with_raw_response.publish() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = await response.parse() + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_publish(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.with_streaming_response.publish() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = await response.parse() + assert_matches_type(PublishPreferencesResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.replace( + section_id="section_id", + name="name", + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + workspace_preference = await async_client.workspace_preferences.replace( + section_id="section_id", + name="name", + description="description", + has_custom_routing=True, + routing_options=["direct_message"], + ) + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.with_raw_response.replace( + section_id="section_id", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.with_streaming_response.replace( + section_id="section_id", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + workspace_preference = await response.parse() + assert_matches_type(WorkspacePreferenceGetResponse, workspace_preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.with_raw_response.replace( + section_id="", + name="name", + ) diff --git a/tests/api_resources/users/__init__.py b/tests/api_resources/users/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/users/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/users/test_preferences.py b/tests/api_resources/users/test_preferences.py new file mode 100644 index 00000000..f791c4f5 --- /dev/null +++ b/tests/api_resources/users/test_preferences.py @@ -0,0 +1,904 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.users import ( + PreferenceRetrieveResponse, + PreferenceBulkUpdateResponse, + PreferenceBulkReplaceResponse, + PreferenceRetrieveTopicResponse, + PreferenceUpdateOrCreateTopicResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestPreferences: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + preference = client.users.preferences.retrieve( + user_id="user_id", + ) + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_with_all_params(self, client: Courier) -> None: + preference = client.users.preferences.retrieve( + user_id="user_id", + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.users.preferences.with_raw_response.retrieve( + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = response.parse() + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.users.preferences.with_streaming_response.retrieve( + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = response.parse() + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.preferences.with_raw_response.retrieve( + user_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_bulk_replace(self, client: Courier) -> None: + preference = client.users.preferences.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_bulk_replace_with_all_params(self, client: Courier) -> None: + preference = client.users.preferences.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + "custom_routing": ["inbox", "email"], + "has_custom_routing": True, + } + ], + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_bulk_replace(self, client: Courier) -> None: + response = client.users.preferences.with_raw_response.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = response.parse() + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_bulk_replace(self, client: Courier) -> None: + with client.users.preferences.with_streaming_response.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = response.parse() + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_bulk_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.preferences.with_raw_response.bulk_replace( + user_id="", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_bulk_update(self, client: Courier) -> None: + preference = client.users.preferences.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_bulk_update_with_all_params(self, client: Courier) -> None: + preference = client.users.preferences.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + "custom_routing": ["inbox", "email"], + "has_custom_routing": True, + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + "custom_routing": ["direct_message"], + "has_custom_routing": True, + }, + ], + tenant_id="tenant_id", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_bulk_update(self, client: Courier) -> None: + response = client.users.preferences.with_raw_response.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = response.parse() + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_bulk_update(self, client: Courier) -> None: + with client.users.preferences.with_streaming_response.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = response.parse() + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_bulk_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.preferences.with_raw_response.bulk_update( + user_id="", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete_topic(self, client: Courier) -> None: + preference = client.users.preferences.delete_topic( + topic_id="topic_id", + user_id="user_id", + ) + assert preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete_topic_with_all_params(self, client: Courier) -> None: + preference = client.users.preferences.delete_topic( + topic_id="topic_id", + user_id="user_id", + tenant_id="tenant_id", + ) + assert preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete_topic(self, client: Courier) -> None: + response = client.users.preferences.with_raw_response.delete_topic( + topic_id="topic_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = response.parse() + assert preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete_topic(self, client: Courier) -> None: + with client.users.preferences.with_streaming_response.delete_topic( + topic_id="topic_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = response.parse() + assert preference is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete_topic(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.preferences.with_raw_response.delete_topic( + topic_id="topic_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.users.preferences.with_raw_response.delete_topic( + topic_id="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_topic(self, client: Courier) -> None: + preference = client.users.preferences.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + ) + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve_topic_with_all_params(self, client: Courier) -> None: + preference = client.users.preferences.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve_topic(self, client: Courier) -> None: + response = client.users.preferences.with_raw_response.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = response.parse() + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve_topic(self, client: Courier) -> None: + with client.users.preferences.with_streaming_response.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = response.parse() + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve_topic(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.preferences.with_raw_response.retrieve_topic( + topic_id="topic_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.users.preferences.with_raw_response.retrieve_topic( + topic_id="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_or_create_topic(self, client: Courier) -> None: + preference = client.users.preferences.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update_or_create_topic_with_all_params(self, client: Courier) -> None: + preference = client.users.preferences.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={ + "status": "OPTED_IN", + "custom_routing": ["inbox", "email"], + "has_custom_routing": True, + }, + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update_or_create_topic(self, client: Courier) -> None: + response = client.users.preferences.with_raw_response.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = response.parse() + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update_or_create_topic(self, client: Courier) -> None: + with client.users.preferences.with_streaming_response.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = response.parse() + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update_or_create_topic(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.preferences.with_raw_response.update_or_create_topic( + topic_id="topic_id", + user_id="", + topic={"status": "OPTED_IN"}, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.users.preferences.with_raw_response.update_or_create_topic( + topic_id="", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) + + +class TestAsyncPreferences: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.retrieve( + user_id="user_id", + ) + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.retrieve( + user_id="user_id", + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.users.preferences.with_raw_response.retrieve( + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = await response.parse() + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.users.preferences.with_streaming_response.retrieve( + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = await response.parse() + assert_matches_type(PreferenceRetrieveResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.preferences.with_raw_response.retrieve( + user_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_bulk_replace(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_bulk_replace_with_all_params(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + "custom_routing": ["inbox", "email"], + "has_custom_routing": True, + } + ], + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_bulk_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.users.preferences.with_raw_response.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = await response.parse() + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_bulk_replace(self, async_client: AsyncCourier) -> None: + async with async_client.users.preferences.with_streaming_response.bulk_replace( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = await response.parse() + assert_matches_type(PreferenceBulkReplaceResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_bulk_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.preferences.with_raw_response.bulk_replace( + user_id="", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_bulk_update(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_bulk_update_with_all_params(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + "custom_routing": ["inbox", "email"], + "has_custom_routing": True, + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + "custom_routing": ["direct_message"], + "has_custom_routing": True, + }, + ], + tenant_id="tenant_id", + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_bulk_update(self, async_client: AsyncCourier) -> None: + response = await async_client.users.preferences.with_raw_response.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = await response.parse() + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_bulk_update(self, async_client: AsyncCourier) -> None: + async with async_client.users.preferences.with_streaming_response.bulk_update( + user_id="user_id", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = await response.parse() + assert_matches_type(PreferenceBulkUpdateResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_bulk_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.preferences.with_raw_response.bulk_update( + user_id="", + topics=[ + { + "status": "OPTED_IN", + "topic_id": "pt_01kx4h2jdafq8bk996nn92357r", + }, + { + "status": "OPTED_OUT", + "topic_id": "pt_01kx4h2jdafq8bk99eyt3dx43x", + }, + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete_topic(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.delete_topic( + topic_id="topic_id", + user_id="user_id", + ) + assert preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete_topic_with_all_params(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.delete_topic( + topic_id="topic_id", + user_id="user_id", + tenant_id="tenant_id", + ) + assert preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete_topic(self, async_client: AsyncCourier) -> None: + response = await async_client.users.preferences.with_raw_response.delete_topic( + topic_id="topic_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = await response.parse() + assert preference is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete_topic(self, async_client: AsyncCourier) -> None: + async with async_client.users.preferences.with_streaming_response.delete_topic( + topic_id="topic_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = await response.parse() + assert preference is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete_topic(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.preferences.with_raw_response.delete_topic( + topic_id="topic_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.users.preferences.with_raw_response.delete_topic( + topic_id="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_topic(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + ) + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve_topic_with_all_params(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve_topic(self, async_client: AsyncCourier) -> None: + response = await async_client.users.preferences.with_raw_response.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = await response.parse() + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve_topic(self, async_client: AsyncCourier) -> None: + async with async_client.users.preferences.with_streaming_response.retrieve_topic( + topic_id="topic_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = await response.parse() + assert_matches_type(PreferenceRetrieveTopicResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve_topic(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.preferences.with_raw_response.retrieve_topic( + topic_id="topic_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.users.preferences.with_raw_response.retrieve_topic( + topic_id="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_or_create_topic(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update_or_create_topic_with_all_params(self, async_client: AsyncCourier) -> None: + preference = await async_client.users.preferences.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={ + "status": "OPTED_IN", + "custom_routing": ["inbox", "email"], + "has_custom_routing": True, + }, + tenant_id="tenant_id", + ) + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update_or_create_topic(self, async_client: AsyncCourier) -> None: + response = await async_client.users.preferences.with_raw_response.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + preference = await response.parse() + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update_or_create_topic(self, async_client: AsyncCourier) -> None: + async with async_client.users.preferences.with_streaming_response.update_or_create_topic( + topic_id="topic_id", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + preference = await response.parse() + assert_matches_type(PreferenceUpdateOrCreateTopicResponse, preference, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update_or_create_topic(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.preferences.with_raw_response.update_or_create_topic( + topic_id="topic_id", + user_id="", + topic={"status": "OPTED_IN"}, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.users.preferences.with_raw_response.update_or_create_topic( + topic_id="", + user_id="user_id", + topic={"status": "OPTED_IN"}, + ) diff --git a/tests/api_resources/users/test_tenants.py b/tests/api_resources/users/test_tenants.py new file mode 100644 index 00000000..856374e8 --- /dev/null +++ b/tests/api_resources/users/test_tenants.py @@ -0,0 +1,534 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.users import ( + TenantListResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTenants: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + tenant = client.users.tenants.list( + user_id="user_id", + ) + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list_with_all_params(self, client: Courier) -> None: + tenant = client.users.tenants.list( + user_id="user_id", + cursor="cursor", + limit=0, + ) + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.users.tenants.with_raw_response.list( + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.users.tenants.with_streaming_response.list( + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tenants.with_raw_response.list( + user_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_multiple(self, client: Courier) -> None: + tenant = client.users.tenants.add_multiple( + user_id="user_id", + tenants=[{"tenant_id": "tenant_id"}], + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_add_multiple(self, client: Courier) -> None: + response = client.users.tenants.with_raw_response.add_multiple( + user_id="user_id", + tenants=[{"tenant_id": "tenant_id"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_add_multiple(self, client: Courier) -> None: + with client.users.tenants.with_streaming_response.add_multiple( + user_id="user_id", + tenants=[{"tenant_id": "tenant_id"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_add_multiple(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tenants.with_raw_response.add_multiple( + user_id="", + tenants=[{"tenant_id": "tenant_id"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_single(self, client: Courier) -> None: + tenant = client.users.tenants.add_single( + tenant_id="tenant_id", + user_id="user_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_single_with_all_params(self, client: Courier) -> None: + tenant = client.users.tenants.add_single( + tenant_id="tenant_id", + user_id="user_id", + profile={"foo": "bar"}, + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_add_single(self, client: Courier) -> None: + response = client.users.tenants.with_raw_response.add_single( + tenant_id="tenant_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_add_single(self, client: Courier) -> None: + with client.users.tenants.with_streaming_response.add_single( + tenant_id="tenant_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_add_single(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tenants.with_raw_response.add_single( + tenant_id="tenant_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.users.tenants.with_raw_response.add_single( + tenant_id="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_remove_all(self, client: Courier) -> None: + tenant = client.users.tenants.remove_all( + "user_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_remove_all(self, client: Courier) -> None: + response = client.users.tenants.with_raw_response.remove_all( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_remove_all(self, client: Courier) -> None: + with client.users.tenants.with_streaming_response.remove_all( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_remove_all(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tenants.with_raw_response.remove_all( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_remove_single(self, client: Courier) -> None: + tenant = client.users.tenants.remove_single( + tenant_id="tenant_id", + user_id="user_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_remove_single(self, client: Courier) -> None: + response = client.users.tenants.with_raw_response.remove_single( + tenant_id="tenant_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_remove_single(self, client: Courier) -> None: + with client.users.tenants.with_streaming_response.remove_single( + tenant_id="tenant_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_remove_single(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tenants.with_raw_response.remove_single( + tenant_id="tenant_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + client.users.tenants.with_raw_response.remove_single( + tenant_id="", + user_id="user_id", + ) + + +class TestAsyncTenants: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.list( + user_id="user_id", + ) + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.list( + user_id="user_id", + cursor="cursor", + limit=0, + ) + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tenants.with_raw_response.list( + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.users.tenants.with_streaming_response.list( + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert_matches_type(TenantListResponse, tenant, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tenants.with_raw_response.list( + user_id="", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_multiple(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.add_multiple( + user_id="user_id", + tenants=[{"tenant_id": "tenant_id"}], + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_add_multiple(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tenants.with_raw_response.add_multiple( + user_id="user_id", + tenants=[{"tenant_id": "tenant_id"}], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_add_multiple(self, async_client: AsyncCourier) -> None: + async with async_client.users.tenants.with_streaming_response.add_multiple( + user_id="user_id", + tenants=[{"tenant_id": "tenant_id"}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_add_multiple(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tenants.with_raw_response.add_multiple( + user_id="", + tenants=[{"tenant_id": "tenant_id"}], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_single(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.add_single( + tenant_id="tenant_id", + user_id="user_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_single_with_all_params(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.add_single( + tenant_id="tenant_id", + user_id="user_id", + profile={"foo": "bar"}, + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_add_single(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tenants.with_raw_response.add_single( + tenant_id="tenant_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_add_single(self, async_client: AsyncCourier) -> None: + async with async_client.users.tenants.with_streaming_response.add_single( + tenant_id="tenant_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_add_single(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tenants.with_raw_response.add_single( + tenant_id="tenant_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.users.tenants.with_raw_response.add_single( + tenant_id="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_remove_all(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.remove_all( + "user_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_remove_all(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tenants.with_raw_response.remove_all( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_remove_all(self, async_client: AsyncCourier) -> None: + async with async_client.users.tenants.with_streaming_response.remove_all( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_remove_all(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tenants.with_raw_response.remove_all( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_remove_single(self, async_client: AsyncCourier) -> None: + tenant = await async_client.users.tenants.remove_single( + tenant_id="tenant_id", + user_id="user_id", + ) + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_remove_single(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tenants.with_raw_response.remove_single( + tenant_id="tenant_id", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + tenant = await response.parse() + assert tenant is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_remove_single(self, async_client: AsyncCourier) -> None: + async with async_client.users.tenants.with_streaming_response.remove_single( + tenant_id="tenant_id", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + tenant = await response.parse() + assert tenant is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_remove_single(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tenants.with_raw_response.remove_single( + tenant_id="tenant_id", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `tenant_id` but received ''"): + await async_client.users.tenants.with_raw_response.remove_single( + tenant_id="", + user_id="user_id", + ) diff --git a/tests/api_resources/users/test_tokens.py b/tests/api_resources/users/test_tokens.py new file mode 100644 index 00000000..f44d4571 --- /dev/null +++ b/tests/api_resources/users/test_tokens.py @@ -0,0 +1,730 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types.users import TokenListResponse, TokenRetrieveResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTokens: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + token = client.users.tokens.retrieve( + token="token", + user_id="user_id", + ) + assert_matches_type(TokenRetrieveResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.users.tokens.with_raw_response.retrieve( + token="token", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = response.parse() + assert_matches_type(TokenRetrieveResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.users.tokens.with_streaming_response.retrieve( + token="token", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = response.parse() + assert_matches_type(TokenRetrieveResponse, token, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tokens.with_raw_response.retrieve( + token="token", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + client.users.tokens.with_raw_response.retrieve( + token="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_update(self, client: Courier) -> None: + token = client.users.tokens.update( + token="token", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_update(self, client: Courier) -> None: + response = client.users.tokens.with_raw_response.update( + token="token", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_update(self, client: Courier) -> None: + with client.users.tokens.with_streaming_response.update( + token="token", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_update(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tokens.with_raw_response.update( + token="token", + user_id="", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + client.users.tokens.with_raw_response.update( + token="", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + token = client.users.tokens.list( + "user_id", + ) + assert_matches_type(TokenListResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.users.tokens.with_raw_response.list( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = response.parse() + assert_matches_type(TokenListResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.users.tokens.with_streaming_response.list( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = response.parse() + assert_matches_type(TokenListResponse, token, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tokens.with_raw_response.list( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: Courier) -> None: + token = client.users.tokens.delete( + token="token", + user_id="user_id", + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: Courier) -> None: + response = client.users.tokens.with_raw_response.delete( + token="token", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: Courier) -> None: + with client.users.tokens.with_streaming_response.delete( + token="token", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tokens.with_raw_response.delete( + token="token", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + client.users.tokens.with_raw_response.delete( + token="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_multiple(self, client: Courier) -> None: + token = client.users.tokens.add_multiple( + "user_id", + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_add_multiple(self, client: Courier) -> None: + response = client.users.tokens.with_raw_response.add_multiple( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_add_multiple(self, client: Courier) -> None: + with client.users.tokens.with_streaming_response.add_multiple( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_add_multiple(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tokens.with_raw_response.add_multiple( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_single(self, client: Courier) -> None: + token = client.users.tokens.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_add_single_with_all_params(self, client: Courier) -> None: + token = client.users.tokens.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + device={ + "ad_id": "ad_id", + "app_id": "app_id", + "device_id": "device_id", + "manufacturer": "manufacturer", + "model": "model", + "platform": "platform", + }, + expiry_date="string", + properties={}, + tracking={ + "ip": "ip", + "lat": "lat", + "long": "long", + "os_version": "os_version", + }, + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_add_single(self, client: Courier) -> None: + response = client.users.tokens.with_raw_response.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_add_single(self, client: Courier) -> None: + with client.users.tokens.with_streaming_response.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_add_single(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + client.users.tokens.with_raw_response.add_single( + token="token", + user_id="", + provider_key="firebase-fcm", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + client.users.tokens.with_raw_response.add_single( + token="", + user_id="user_id", + provider_key="firebase-fcm", + ) + + +class TestAsyncTokens: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.retrieve( + token="token", + user_id="user_id", + ) + assert_matches_type(TokenRetrieveResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tokens.with_raw_response.retrieve( + token="token", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = await response.parse() + assert_matches_type(TokenRetrieveResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.users.tokens.with_streaming_response.retrieve( + token="token", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = await response.parse() + assert_matches_type(TokenRetrieveResponse, token, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tokens.with_raw_response.retrieve( + token="token", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + await async_client.users.tokens.with_raw_response.retrieve( + token="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_update(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.update( + token="token", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_update(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tokens.with_raw_response.update( + token="token", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = await response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_update(self, async_client: AsyncCourier) -> None: + async with async_client.users.tokens.with_streaming_response.update( + token="token", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = await response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_update(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tokens.with_raw_response.update( + token="token", + user_id="", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + await async_client.users.tokens.with_raw_response.update( + token="", + user_id="user_id", + patch=[ + { + "op": "op", + "path": "path", + } + ], + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.list( + "user_id", + ) + assert_matches_type(TokenListResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tokens.with_raw_response.list( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = await response.parse() + assert_matches_type(TokenListResponse, token, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.users.tokens.with_streaming_response.list( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = await response.parse() + assert_matches_type(TokenListResponse, token, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tokens.with_raw_response.list( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.delete( + token="token", + user_id="user_id", + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tokens.with_raw_response.delete( + token="token", + user_id="user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = await response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncCourier) -> None: + async with async_client.users.tokens.with_streaming_response.delete( + token="token", + user_id="user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = await response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tokens.with_raw_response.delete( + token="token", + user_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + await async_client.users.tokens.with_raw_response.delete( + token="", + user_id="user_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_multiple(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.add_multiple( + "user_id", + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_add_multiple(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tokens.with_raw_response.add_multiple( + "user_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = await response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_add_multiple(self, async_client: AsyncCourier) -> None: + async with async_client.users.tokens.with_streaming_response.add_multiple( + "user_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = await response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_add_multiple(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tokens.with_raw_response.add_multiple( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_single(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_add_single_with_all_params(self, async_client: AsyncCourier) -> None: + token = await async_client.users.tokens.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + device={ + "ad_id": "ad_id", + "app_id": "app_id", + "device_id": "device_id", + "manufacturer": "manufacturer", + "model": "model", + "platform": "platform", + }, + expiry_date="string", + properties={}, + tracking={ + "ip": "ip", + "lat": "lat", + "long": "long", + "os_version": "os_version", + }, + ) + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_add_single(self, async_client: AsyncCourier) -> None: + response = await async_client.users.tokens.with_raw_response.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + token = await response.parse() + assert token is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_add_single(self, async_client: AsyncCourier) -> None: + async with async_client.users.tokens.with_streaming_response.add_single( + token="token", + user_id="user_id", + provider_key="firebase-fcm", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + token = await response.parse() + assert token is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_add_single(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `user_id` but received ''"): + await async_client.users.tokens.with_raw_response.add_single( + token="token", + user_id="", + provider_key="firebase-fcm", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `token` but received ''"): + await async_client.users.tokens.with_raw_response.add_single( + token="", + user_id="user_id", + provider_key="firebase-fcm", + ) diff --git a/tests/api_resources/workspace_preferences/__init__.py b/tests/api_resources/workspace_preferences/__init__.py new file mode 100644 index 00000000..fd8019a9 --- /dev/null +++ b/tests/api_resources/workspace_preferences/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/workspace_preferences/test_topics.py b/tests/api_resources/workspace_preferences/test_topics.py new file mode 100644 index 00000000..0d6e92de --- /dev/null +++ b/tests/api_resources/workspace_preferences/test_topics.py @@ -0,0 +1,606 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from courier import Courier, AsyncCourier +from tests.utils import assert_matches_type +from courier.types import WorkspacePreferenceTopicGetResponse, WorkspacePreferenceTopicListResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + + +class TestTopics: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_create_with_all_params(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + allowed_preferences=["snooze"], + description="description", + include_unsubscribe_header=True, + routing_options=["direct_message"], + topic_data={"foo": "bar"}, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_create(self, client: Courier) -> None: + response = client.workspace_preferences.topics.with_raw_response.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_create(self, client: Courier) -> None: + with client.workspace_preferences.topics.with_streaming_response.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_create(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.create( + section_id="", + default_status="OPTED_OUT", + name="Marketing", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_retrieve(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.retrieve( + topic_id="topic_id", + section_id="section_id", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_retrieve(self, client: Courier) -> None: + response = client.workspace_preferences.topics.with_raw_response.retrieve( + topic_id="topic_id", + section_id="section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_retrieve(self, client: Courier) -> None: + with client.workspace_preferences.topics.with_streaming_response.retrieve( + topic_id="topic_id", + section_id="section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_retrieve(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.retrieve( + topic_id="topic_id", + section_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.retrieve( + topic_id="", + section_id="section_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_list(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.list( + "section_id", + ) + assert_matches_type(WorkspacePreferenceTopicListResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_list(self, client: Courier) -> None: + response = client.workspace_preferences.topics.with_raw_response.list( + "section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicListResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_list(self, client: Courier) -> None: + with client.workspace_preferences.topics.with_streaming_response.list( + "section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicListResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_list(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.list( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_archive(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.archive( + topic_id="topic_id", + section_id="section_id", + ) + assert topic is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_archive(self, client: Courier) -> None: + response = client.workspace_preferences.topics.with_raw_response.archive( + topic_id="topic_id", + section_id="section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = response.parse() + assert topic is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_archive(self, client: Courier) -> None: + with client.workspace_preferences.topics.with_streaming_response.archive( + topic_id="topic_id", + section_id="section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = response.parse() + assert topic is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_archive(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.archive( + topic_id="topic_id", + section_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.archive( + topic_id="", + section_id="section_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_replace_with_all_params(self, client: Courier) -> None: + topic = client.workspace_preferences.topics.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + allowed_preferences=["snooze"], + description="description", + include_unsubscribe_header=True, + routing_options=["direct_message"], + topic_data={"foo": "bar"}, + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_replace(self, client: Courier) -> None: + response = client.workspace_preferences.topics.with_raw_response.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_replace(self, client: Courier) -> None: + with client.workspace_preferences.topics.with_streaming_response.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_replace(self, client: Courier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.replace( + topic_id="topic_id", + section_id="", + default_status="OPTED_OUT", + name="name", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + client.workspace_preferences.topics.with_raw_response.replace( + topic_id="", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) + + +class TestAsyncTopics: + parametrize = pytest.mark.parametrize( + "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + allowed_preferences=["snooze"], + description="description", + include_unsubscribe_header=True, + routing_options=["direct_message"], + topic_data={"foo": "bar"}, + idempotency_key="order-ORD-456-user-123", + x_idempotency_expiration="1785312000", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_create(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.topics.with_raw_response.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_create(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.topics.with_streaming_response.create( + section_id="section_id", + default_status="OPTED_OUT", + name="Marketing", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_create(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.create( + section_id="", + default_status="OPTED_OUT", + name="Marketing", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_retrieve(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.retrieve( + topic_id="topic_id", + section_id="section_id", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.topics.with_raw_response.retrieve( + topic_id="topic_id", + section_id="section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.topics.with_streaming_response.retrieve( + topic_id="topic_id", + section_id="section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.retrieve( + topic_id="topic_id", + section_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.retrieve( + topic_id="", + section_id="section_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_list(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.list( + "section_id", + ) + assert_matches_type(WorkspacePreferenceTopicListResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_list(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.topics.with_raw_response.list( + "section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicListResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_list(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.topics.with_streaming_response.list( + "section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicListResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_list(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.list( + "", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_archive(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.archive( + topic_id="topic_id", + section_id="section_id", + ) + assert topic is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_archive(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.topics.with_raw_response.archive( + topic_id="topic_id", + section_id="section_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = await response.parse() + assert topic is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_archive(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.topics.with_streaming_response.archive( + topic_id="topic_id", + section_id="section_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = await response.parse() + assert topic is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_archive(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.archive( + topic_id="topic_id", + section_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.archive( + topic_id="", + section_id="section_id", + ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_replace_with_all_params(self, async_client: AsyncCourier) -> None: + topic = await async_client.workspace_preferences.topics.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + allowed_preferences=["snooze"], + description="description", + include_unsubscribe_header=True, + routing_options=["direct_message"], + topic_data={"foo": "bar"}, + ) + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_replace(self, async_client: AsyncCourier) -> None: + response = await async_client.workspace_preferences.topics.with_raw_response.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_replace(self, async_client: AsyncCourier) -> None: + async with async_client.workspace_preferences.topics.with_streaming_response.replace( + topic_id="topic_id", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + topic = await response.parse() + assert_matches_type(WorkspacePreferenceTopicGetResponse, topic, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_replace(self, async_client: AsyncCourier) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `section_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.replace( + topic_id="topic_id", + section_id="", + default_status="OPTED_OUT", + name="name", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `topic_id` but received ''"): + await async_client.workspace_preferences.topics.with_raw_response.replace( + topic_id="", + section_id="section_id", + default_status="OPTED_OUT", + name="name", + ) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..fb6fecfe --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,84 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +import logging +from typing import TYPE_CHECKING, Iterator, AsyncIterator + +import httpx +import pytest +from pytest_asyncio import is_async_test + +from courier import Courier, AsyncCourier, DefaultAioHttpClient +from courier._utils import is_dict + +if TYPE_CHECKING: + from _pytest.fixtures import FixtureRequest # pyright: ignore[reportPrivateImportUsage] + +pytest.register_assert_rewrite("tests.utils") + +logging.getLogger("courier").setLevel(logging.DEBUG) + + +# automatically add `pytest.mark.asyncio()` to all of our async tests +# so we don't have to add that boilerplate everywhere +def pytest_collection_modifyitems(items: list[pytest.Function]) -> None: + pytest_asyncio_tests = (item for item in items if is_async_test(item)) + session_scope_marker = pytest.mark.asyncio(loop_scope="session") + for async_test in pytest_asyncio_tests: + async_test.add_marker(session_scope_marker, append=False) + + # We skip tests that use both the aiohttp client and respx_mock as respx_mock + # doesn't support custom transports. + for item in items: + if "async_client" not in item.fixturenames or "respx_mock" not in item.fixturenames: + continue + + if not hasattr(item, "callspec"): + continue + + async_client_param = item.callspec.params.get("async_client") + if is_dict(async_client_param) and async_client_param.get("http_client") == "aiohttp": + item.add_marker(pytest.mark.skip(reason="aiohttp client is not compatible with respx_mock")) + + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") + +api_key = "My API Key" + + +@pytest.fixture(scope="session") +def client(request: FixtureRequest) -> Iterator[Courier]: + strict = getattr(request, "param", True) + if not isinstance(strict, bool): + raise TypeError(f"Unexpected fixture parameter type {type(strict)}, expected {bool}") + + with Courier(base_url=base_url, api_key=api_key, _strict_response_validation=strict) as client: + yield client + + +@pytest.fixture(scope="session") +async def async_client(request: FixtureRequest) -> AsyncIterator[AsyncCourier]: + param = getattr(request, "param", True) + + # defaults + strict = True + http_client: None | httpx.AsyncClient = None + + if isinstance(param, bool): + strict = param + elif is_dict(param): + strict = param.get("strict", True) + assert isinstance(strict, bool) + + http_client_type = param.get("http_client", "httpx") + if http_client_type == "aiohttp": + http_client = DefaultAioHttpClient() + else: + raise TypeError(f"Unexpected fixture parameter type {type(param)}, expected bool or dict") + + async with AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=strict, http_client=http_client + ) as client: + yield client diff --git a/tests/sample_file.txt b/tests/sample_file.txt new file mode 100644 index 00000000..af5626b4 --- /dev/null +++ b/tests/sample_file.txt @@ -0,0 +1 @@ +Hello, world! diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 00000000..30d1d914 --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,1964 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import gc +import os +import sys +import json +import asyncio +import inspect +import dataclasses +import tracemalloc +from typing import Any, Union, TypeVar, Callable, Iterable, Iterator, Optional, Coroutine, cast +from unittest import mock +from typing_extensions import Literal, AsyncIterator, override + +import httpx +import pytest +from respx import MockRouter +from pydantic import ValidationError + +from courier import Courier, AsyncCourier, APIResponseValidationError +from courier._types import Omit +from courier._utils import asyncify +from courier._models import BaseModel, FinalRequestOptions +from courier._exceptions import CourierError, APIStatusError, APITimeoutError, APIResponseValidationError +from courier._base_client import ( + DEFAULT_TIMEOUT, + HTTPX_DEFAULT_TIMEOUT, + BaseClient, + OtherPlatform, + DefaultHttpxClient, + DefaultAsyncHttpxClient, + get_platform, + make_request_options, +) + +from .utils import update_env + +T = TypeVar("T") +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") +api_key = "My API Key" + + +def _get_params(client: BaseClient[Any, Any]) -> dict[str, str]: + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + url = httpx.URL(request.url) + return dict(url.params) + + +def _low_retry_timeout(*_args: Any, **_kwargs: Any) -> float: + return 0.1 + + +def mirror_request_content(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, content=request.content) + + +# note: we can't use the httpx.MockTransport class as it consumes the request +# body itself, which means we can't test that the body is read lazily +class MockTransport(httpx.BaseTransport, httpx.AsyncBaseTransport): + def __init__( + self, + handler: Callable[[httpx.Request], httpx.Response] + | Callable[[httpx.Request], Coroutine[Any, Any, httpx.Response]], + ) -> None: + self.handler = handler + + @override + def handle_request( + self, + request: httpx.Request, + ) -> httpx.Response: + assert not inspect.iscoroutinefunction(self.handler), "handler must not be a coroutine function" + assert inspect.isfunction(self.handler), "handler must be a function" + return self.handler(request) + + @override + async def handle_async_request( + self, + request: httpx.Request, + ) -> httpx.Response: + assert inspect.iscoroutinefunction(self.handler), "handler must be a coroutine function" + return await self.handler(request) + + +@dataclasses.dataclass +class Counter: + value: int = 0 + + +def _make_sync_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> Iterator[T]: + for item in iterable: + if counter: + counter.value += 1 + yield item + + +async def _make_async_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> AsyncIterator[T]: + for item in iterable: + if counter: + counter.value += 1 + yield item + + +def _get_open_connections(client: Courier | AsyncCourier) -> int: + transport = client._client._transport + assert isinstance(transport, httpx.HTTPTransport) or isinstance(transport, httpx.AsyncHTTPTransport) + + pool = transport._pool + return len(pool._requests) + + +class TestCourier: + @pytest.mark.respx(base_url=base_url) + def test_raw_response(self, respx_mock: MockRouter, client: Courier) -> None: + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == {"foo": "bar"} + + @pytest.mark.respx(base_url=base_url) + def test_raw_response_for_binary(self, respx_mock: MockRouter, client: Courier) -> None: + respx_mock.post("/foo").mock( + return_value=httpx.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}') + ) + + response = client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == {"foo": "bar"} + + def test_copy(self, client: Courier) -> None: + copied = client.copy() + assert id(copied) != id(client) + + copied = client.copy(api_key="another My API Key") + assert copied.api_key == "another My API Key" + assert client.api_key == "My API Key" + + def test_copy_default_options(self, client: Courier) -> None: + # options that have a default are overridden correctly + copied = client.copy(max_retries=7) + assert copied.max_retries == 7 + assert client.max_retries == 2 + + copied2 = copied.copy(max_retries=6) + assert copied2.max_retries == 6 + assert copied.max_retries == 7 + + # timeout + assert isinstance(client.timeout, httpx.Timeout) + copied = client.copy(timeout=None) + assert copied.timeout is None + assert isinstance(client.timeout, httpx.Timeout) + + def test_copy_default_headers(self) -> None: + client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + assert client.default_headers["X-Foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert copied.default_headers["X-Foo"] == "bar" + + # merges already given headers + copied = client.copy(default_headers={"X-Bar": "stainless"}) + assert copied.default_headers["X-Foo"] == "bar" + assert copied.default_headers["X-Bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_headers={"X-Foo": "stainless"}) + assert copied.default_headers["X-Foo"] == "stainless" + + # set_default_headers + + # completely overrides already set values + copied = client.copy(set_default_headers={}) + assert copied.default_headers.get("X-Foo") is None + + copied = client.copy(set_default_headers={"X-Bar": "Robert"}) + assert copied.default_headers["X-Bar"] == "Robert" + + with pytest.raises( + ValueError, + match="`default_headers` and `set_default_headers` arguments are mutually exclusive", + ): + client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"}) + client.close() + + def test_copy_default_query(self) -> None: + client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"} + ) + assert _get_params(client)["foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert _get_params(copied)["foo"] == "bar" + + # merges already given params + copied = client.copy(default_query={"bar": "stainless"}) + params = _get_params(copied) + assert params["foo"] == "bar" + assert params["bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_query={"foo": "stainless"}) + assert _get_params(copied)["foo"] == "stainless" + + # set_default_query + + # completely overrides already set values + copied = client.copy(set_default_query={}) + assert _get_params(copied) == {} + + copied = client.copy(set_default_query={"bar": "Robert"}) + assert _get_params(copied)["bar"] == "Robert" + + with pytest.raises( + ValueError, + # TODO: update + match="`default_query` and `set_default_query` arguments are mutually exclusive", + ): + client.copy(set_default_query={}, default_query={"foo": "Bar"}) + + client.close() + + def test_copy_signature(self, client: Courier) -> None: + # ensure the same parameters that can be passed to the client are defined in the `.copy()` method + init_signature = inspect.signature( + # mypy doesn't like that we access the `__init__` property. + client.__init__, # type: ignore[misc] + ) + copy_signature = inspect.signature(client.copy) + exclude_params = {"transport", "proxies", "_strict_response_validation"} + + for name in init_signature.parameters.keys(): + if name in exclude_params: + continue + + copy_param = copy_signature.parameters.get(name) + assert copy_param is not None, f"copy() signature is missing the {name} param" + + @pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12") + def test_copy_build_request(self, client: Courier) -> None: + options = FinalRequestOptions(method="get", url="/foo") + + def build_request(options: FinalRequestOptions) -> None: + client_copy = client.copy() + client_copy._build_request(options) + + # ensure that the machinery is warmed up before tracing starts. + build_request(options) + gc.collect() + + tracemalloc.start(1000) + + snapshot_before = tracemalloc.take_snapshot() + + ITERATIONS = 10 + for _ in range(ITERATIONS): + build_request(options) + + gc.collect() + snapshot_after = tracemalloc.take_snapshot() + + tracemalloc.stop() + + def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None: + if diff.count == 0: + # Avoid false positives by considering only leaks (i.e. allocations that persist). + return + + if diff.count % ITERATIONS != 0: + # Avoid false positives by considering only leaks that appear per iteration. + return + + for frame in diff.traceback: + if any( + frame.filename.endswith(fragment) + for fragment in [ + # to_raw_response_wrapper leaks through the @functools.wraps() decorator. + # + # removing the decorator fixes the leak for reasons we don't understand. + "courier/_legacy_response.py", + "courier/_response.py", + # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. + "courier/_compat.py", + # Standard library leaks we don't care about. + "/logging/__init__.py", + ] + ): + return + + leaks.append(diff) + + leaks: list[tracemalloc.StatisticDiff] = [] + for diff in snapshot_after.compare_to(snapshot_before, "traceback"): + add_leak(leaks, diff) + if leaks: + for leak in leaks: + print("MEMORY LEAK:", leak) + for frame in leak.traceback: + print(frame) + raise AssertionError() + + def test_request_timeout(self, client: Courier) -> None: + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + request = client._build_request(FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0))) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(100.0) + + def test_client_timeout_option(self) -> None: + client = Courier(base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=httpx.Timeout(0)) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(0) + + client.close() + + def test_http_client_timeout_option(self) -> None: + # custom timeout given to the httpx client should be used + with httpx.Client(timeout=None) as http_client: + client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(None) + + client.close() + + # no timeout given to the httpx client should not use the httpx default + with httpx.Client() as http_client: + client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + client.close() + + # explicitly passing the default timeout currently results in it being ignored + with httpx.Client(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client: + client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT # our default + + client.close() + + async def test_invalid_http_client(self) -> None: + with pytest.raises(TypeError, match="Invalid `http_client` arg"): + async with httpx.AsyncClient() as http_client: + Courier( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=cast(Any, http_client), + ) + + def test_default_headers_option(self) -> None: + test_client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + request = test_client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "bar" + assert request.headers.get("x-stainless-lang") == "python" + + test_client2 = Courier( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + default_headers={ + "X-Foo": "stainless", + "X-Stainless-Lang": "my-overriding-header", + }, + ) + request = test_client2._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "stainless" + assert request.headers.get("x-stainless-lang") == "my-overriding-header" + + test_client.close() + test_client2.close() + + def test_validate_headers(self) -> None: + client = Courier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("Authorization") == f"Bearer {api_key}" + + with pytest.raises(CourierError): + with update_env(**{"COURIER_API_KEY": Omit()}): + client2 = Courier(base_url=base_url, api_key=None, _strict_response_validation=True) + _ = client2 + + def test_default_query_option(self) -> None: + client = Courier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"} + ) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + url = httpx.URL(request.url) + assert dict(url.params) == {"query_param": "bar"} + + request = client._build_request( + FinalRequestOptions( + method="get", + url="/foo", + params={"foo": "baz", "query_param": "overridden"}, + ) + ) + url = httpx.URL(request.url) + assert dict(url.params) == {"foo": "baz", "query_param": "overridden"} + + client.close() + + def test_hardcoded_query_params_in_url(self, client: Courier) -> None: + request = client._build_request(FinalRequestOptions(method="get", url="/foo?beta=true")) + url = httpx.URL(request.url) + assert dict(url.params) == {"beta": "true"} + + request = client._build_request( + FinalRequestOptions( + method="get", + url="/foo?beta=true", + params={"limit": "10", "page": "abc"}, + ) + ) + url = httpx.URL(request.url) + assert dict(url.params) == {"beta": "true", "limit": "10", "page": "abc"} + + request = client._build_request( + FinalRequestOptions( + method="get", + url="/files/a%2Fb?beta=true", + params={"limit": "10"}, + ) + ) + assert request.url.raw_path == b"/files/a%2Fb?beta=true&limit=10" + + def test_request_extra_json(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": False} + + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"baz": False} + + # `extra_json` takes priority over `json_data` when keys clash + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar", "baz": True}, + extra_json={"baz": None}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": None} + + def test_request_extra_headers(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options(extra_headers={"X-Foo": "Foo"}), + ), + ) + assert request.headers.get("X-Foo") == "Foo" + + # `extra_headers` takes priority over `default_headers` when keys clash + request = client.with_options(default_headers={"X-Bar": "true"})._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_headers={"X-Bar": "false"}, + ), + ), + ) + assert request.headers.get("X-Bar") == "false" + + def test_request_extra_query(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_query={"my_query_param": "Foo"}, + ), + ), + ) + params = dict(request.url.params) + assert params == {"my_query_param": "Foo"} + + # if both `query` and `extra_query` are given, they are merged + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"bar": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = dict(request.url.params) + assert params == {"bar": "1", "foo": "2"} + + # `extra_query` takes priority over `query` when keys clash + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"foo": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = dict(request.url.params) + assert params == {"foo": "2"} + + def test_multipart_repeating_array(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/foo", + headers={"Content-Type": "multipart/form-data; boundary=6b7ba517decee4a450543ea6ae821c82"}, + json_data={"array": ["foo", "bar"]}, + files=[("foo.txt", b"hello world")], + ) + ) + + assert request.read().split(b"\r\n") == [ + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"foo", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"bar", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="foo.txt"; filename="upload"', + b"Content-Type: application/octet-stream", + b"", + b"hello world", + b"--6b7ba517decee4a450543ea6ae821c82--", + b"", + ] + + @pytest.mark.respx(base_url=base_url) + def test_binary_content_upload(self, respx_mock: MockRouter, client: Courier) -> None: + respx_mock.post("/upload").mock(side_effect=mirror_request_content) + + file_content = b"Hello, this is a test file." + + response = client.post( + "/upload", + content=file_content, + cast_to=httpx.Response, + options={"headers": {"Content-Type": "application/octet-stream"}}, + ) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == "application/octet-stream" + assert response.content == file_content + + def test_binary_content_upload_with_iterator(self) -> None: + file_content = b"Hello, this is a test file." + counter = Counter() + iterator = _make_sync_iterator([file_content], counter=counter) + + def mock_handler(request: httpx.Request) -> httpx.Response: + assert counter.value == 0, "the request body should not have been read" + return httpx.Response(200, content=request.read()) + + with Courier( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(transport=MockTransport(handler=mock_handler)), + ) as client: + response = client.post( + "/upload", + content=iterator, + cast_to=httpx.Response, + options={"headers": {"Content-Type": "application/octet-stream"}}, + ) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == "application/octet-stream" + assert response.content == file_content + assert counter.value == 1 + + @pytest.mark.respx(base_url=base_url) + def test_binary_content_upload_with_body_is_deprecated(self, respx_mock: MockRouter, client: Courier) -> None: + respx_mock.post("/upload").mock(side_effect=mirror_request_content) + + file_content = b"Hello, this is a test file." + + with pytest.deprecated_call( + match="Passing raw bytes as `body` is deprecated and will be removed in a future version. Please pass raw bytes via the `content` parameter instead." + ): + response = client.post( + "/upload", + body=file_content, + cast_to=httpx.Response, + options={"headers": {"Content-Type": "application/octet-stream"}}, + ) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == "application/octet-stream" + assert response.content == file_content + + @pytest.mark.respx(base_url=base_url) + def test_basic_union_response(self, respx_mock: MockRouter, client: Courier) -> None: + class Model1(BaseModel): + name: str + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + @pytest.mark.respx(base_url=base_url) + def test_union_response_different_types(self, respx_mock: MockRouter, client: Courier) -> None: + """Union of objects with the same field name using a different type""" + + class Model1(BaseModel): + foo: int + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": 1})) + + response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model1) + assert response.foo == 1 + + @pytest.mark.respx(base_url=base_url) + def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter, client: Courier) -> None: + """ + Response that sets Content-Type to something other than application/json but returns json data + """ + + class Model(BaseModel): + foo: int + + respx_mock.get("/foo").mock( + return_value=httpx.Response( + 200, + content=json.dumps({"foo": 2}), + headers={"Content-Type": "application/text"}, + ) + ) + + response = client.get("/foo", cast_to=Model) + assert isinstance(response, Model) + assert response.foo == 2 + + def test_base_url_setter(self) -> None: + client = Courier(base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True) + assert client.base_url == "https://example.com/from_init/" + + client.base_url = "https://example.com/from_setter" # type: ignore[assignment] + + assert client.base_url == "https://example.com/from_setter/" + + client.close() + + def test_base_url_env(self) -> None: + with update_env(COURIER_BASE_URL="http://localhost:5000/from/env"): + client = Courier(api_key=api_key, _strict_response_validation=True) + assert client.base_url == "http://localhost:5000/from/env/" + + @pytest.mark.parametrize( + "client", + [ + Courier(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True), + Courier( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_base_url_trailing_slash(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + client.close() + + @pytest.mark.parametrize( + "client", + [ + Courier(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True), + Courier( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_base_url_no_trailing_slash(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + client.close() + + @pytest.mark.parametrize( + "client", + [ + Courier(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True), + Courier( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_absolute_request_url(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="https://myapi.com/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "https://myapi.com/foo" + client.close() + + def test_copied_client_does_not_close_http(self) -> None: + test_client = Courier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + assert not test_client.is_closed() + + copied = test_client.copy() + assert copied is not test_client + + del copied + + assert not test_client.is_closed() + + def test_client_context_manager(self) -> None: + test_client = Courier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + with test_client as c2: + assert c2 is test_client + assert not c2.is_closed() + assert not test_client.is_closed() + assert test_client.is_closed() + + @pytest.mark.respx(base_url=base_url) + def test_client_response_validation_error(self, respx_mock: MockRouter, client: Courier) -> None: + class Model(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": {"invalid": True}})) + + with pytest.raises(APIResponseValidationError) as exc: + client.get("/foo", cast_to=Model) + + assert isinstance(exc.value.__cause__, ValidationError) + + def test_client_max_retries_validation(self) -> None: + with pytest.raises(TypeError, match=r"max_retries cannot be None"): + Courier(base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=cast(Any, None)) + + @pytest.mark.respx(base_url=base_url) + def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + name: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, text="my-custom-format")) + + strict_client = Courier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + with pytest.raises(APIResponseValidationError): + strict_client.get("/foo", cast_to=Model) + + non_strict_client = Courier(base_url=base_url, api_key=api_key, _strict_response_validation=False) + + response = non_strict_client.get("/foo", cast_to=Model) + assert isinstance(response, str) # type: ignore[unreachable] + + strict_client.close() + non_strict_client.close() + + @pytest.mark.parametrize( + "remaining_retries,retry_after,timeout", + [ + [3, "20", 20], + [3, "0", 0.5], + [3, "-10", 0.5], + [3, "60", 60], + [3, "61", 0.5], + [3, "Fri, 29 Sep 2023 16:26:57 GMT", 20], + [3, "Fri, 29 Sep 2023 16:26:37 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:27:37 GMT", 60], + [3, "Fri, 29 Sep 2023 16:27:38 GMT", 0.5], + [3, "99999999999999999999999999999999999", 0.5], + [3, "Zun, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "", 0.5], + [2, "", 0.5 * 2.0], + [1, "", 0.5 * 4.0], + [-1100, "", 8], # test large number potentially overflowing + ], + ) + @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) + def test_parse_retry_after_header( + self, remaining_retries: int, retry_after: str, timeout: float, client: Courier + ) -> None: + headers = httpx.Headers({"retry-after": retry_after}) + options = FinalRequestOptions(method="get", url="/foo", max_retries=3) + calculated = client._calculate_retry_timeout(remaining_retries, options, headers) + assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter, client: Courier) -> None: + respx_mock.post("/send").mock(side_effect=httpx.TimeoutException("Test timeout error")) + + with pytest.raises(APITimeoutError): + client.send.with_streaming_response.message(message={}).__enter__() + + assert _get_open_connections(client) == 0 + + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter, client: Courier) -> None: + respx_mock.post("/send").mock(return_value=httpx.Response(500)) + + with pytest.raises(APIStatusError): + client.send.with_streaming_response.message(message={}).__enter__() + assert _get_open_connections(client) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + @pytest.mark.parametrize("failure_mode", ["status", "exception"]) + def test_retries_taken( + self, + client: Courier, + failures_before_success: int, + failure_mode: Literal["status", "exception"], + respx_mock: MockRouter, + ) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + if failure_mode == "exception": + raise RuntimeError("oops") + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/send").mock(side_effect=retry_handler) + + response = client.send.with_raw_response.message(message={}) + + assert response.retries_taken == failures_before_success + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_omit_retry_count_header( + self, client: Courier, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/send").mock(side_effect=retry_handler) + + response = client.send.with_raw_response.message(message={}, extra_headers={"x-stainless-retry-count": Omit()}) + + assert len(response.http_request.headers.get_list("x-stainless-retry-count")) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_overwrite_retry_count_header( + self, client: Courier, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/send").mock(side_effect=retry_handler) + + response = client.send.with_raw_response.message(message={}, extra_headers={"x-stainless-retry-count": "42"}) + + assert response.http_request.headers.get("x-stainless-retry-count") == "42" + + def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None: + # Test that the proxy environment variables are set correctly + monkeypatch.setenv("HTTPS_PROXY", "https://example.org") + # Delete in case our environment has any proxy env vars set + monkeypatch.delenv("HTTP_PROXY", raising=False) + monkeypatch.delenv("ALL_PROXY", raising=False) + monkeypatch.delenv("NO_PROXY", raising=False) + monkeypatch.delenv("http_proxy", raising=False) + monkeypatch.delenv("https_proxy", raising=False) + monkeypatch.delenv("all_proxy", raising=False) + monkeypatch.delenv("no_proxy", raising=False) + + client = DefaultHttpxClient() + + mounts = tuple(client._mounts.items()) + assert len(mounts) == 1 + assert mounts[0][0].pattern == "https://" + + @pytest.mark.filterwarnings("ignore:.*deprecated.*:DeprecationWarning") + def test_default_client_creation(self) -> None: + # Ensure that the client can be initialized without any exceptions + DefaultHttpxClient( + verify=True, + cert=None, + trust_env=True, + http1=True, + http2=False, + limits=httpx.Limits(max_connections=100, max_keepalive_connections=20), + ) + + @pytest.mark.respx(base_url=base_url) + def test_follow_redirects(self, respx_mock: MockRouter, client: Courier) -> None: + # Test that the default follow_redirects=True allows following redirects + respx_mock.post("/redirect").mock( + return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"}) + ) + respx_mock.get("/redirected").mock(return_value=httpx.Response(200, json={"status": "ok"})) + + response = client.post("/redirect", body={"key": "value"}, cast_to=httpx.Response) + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + @pytest.mark.respx(base_url=base_url) + def test_follow_redirects_disabled(self, respx_mock: MockRouter, client: Courier) -> None: + # Test that follow_redirects=False prevents following redirects + respx_mock.post("/redirect").mock( + return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"}) + ) + + with pytest.raises(APIStatusError) as exc_info: + client.post("/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx.Response) + + assert exc_info.value.response.status_code == 302 + assert exc_info.value.response.headers["Location"] == f"{base_url}/redirected" + + +class TestAsyncCourier: + @pytest.mark.respx(base_url=base_url) + async def test_raw_response(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = await async_client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == {"foo": "bar"} + + @pytest.mark.respx(base_url=base_url) + async def test_raw_response_for_binary(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + respx_mock.post("/foo").mock( + return_value=httpx.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}') + ) + + response = await async_client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == {"foo": "bar"} + + def test_copy(self, async_client: AsyncCourier) -> None: + copied = async_client.copy() + assert id(copied) != id(async_client) + + copied = async_client.copy(api_key="another My API Key") + assert copied.api_key == "another My API Key" + assert async_client.api_key == "My API Key" + + def test_copy_default_options(self, async_client: AsyncCourier) -> None: + # options that have a default are overridden correctly + copied = async_client.copy(max_retries=7) + assert copied.max_retries == 7 + assert async_client.max_retries == 2 + + copied2 = copied.copy(max_retries=6) + assert copied2.max_retries == 6 + assert copied.max_retries == 7 + + # timeout + assert isinstance(async_client.timeout, httpx.Timeout) + copied = async_client.copy(timeout=None) + assert copied.timeout is None + assert isinstance(async_client.timeout, httpx.Timeout) + + async def test_copy_default_headers(self) -> None: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + assert client.default_headers["X-Foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert copied.default_headers["X-Foo"] == "bar" + + # merges already given headers + copied = client.copy(default_headers={"X-Bar": "stainless"}) + assert copied.default_headers["X-Foo"] == "bar" + assert copied.default_headers["X-Bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_headers={"X-Foo": "stainless"}) + assert copied.default_headers["X-Foo"] == "stainless" + + # set_default_headers + + # completely overrides already set values + copied = client.copy(set_default_headers={}) + assert copied.default_headers.get("X-Foo") is None + + copied = client.copy(set_default_headers={"X-Bar": "Robert"}) + assert copied.default_headers["X-Bar"] == "Robert" + + with pytest.raises( + ValueError, + match="`default_headers` and `set_default_headers` arguments are mutually exclusive", + ): + client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"}) + await client.close() + + async def test_copy_default_query(self) -> None: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"} + ) + assert _get_params(client)["foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert _get_params(copied)["foo"] == "bar" + + # merges already given params + copied = client.copy(default_query={"bar": "stainless"}) + params = _get_params(copied) + assert params["foo"] == "bar" + assert params["bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_query={"foo": "stainless"}) + assert _get_params(copied)["foo"] == "stainless" + + # set_default_query + + # completely overrides already set values + copied = client.copy(set_default_query={}) + assert _get_params(copied) == {} + + copied = client.copy(set_default_query={"bar": "Robert"}) + assert _get_params(copied)["bar"] == "Robert" + + with pytest.raises( + ValueError, + # TODO: update + match="`default_query` and `set_default_query` arguments are mutually exclusive", + ): + client.copy(set_default_query={}, default_query={"foo": "Bar"}) + + await client.close() + + def test_copy_signature(self, async_client: AsyncCourier) -> None: + # ensure the same parameters that can be passed to the client are defined in the `.copy()` method + init_signature = inspect.signature( + # mypy doesn't like that we access the `__init__` property. + async_client.__init__, # type: ignore[misc] + ) + copy_signature = inspect.signature(async_client.copy) + exclude_params = {"transport", "proxies", "_strict_response_validation"} + + for name in init_signature.parameters.keys(): + if name in exclude_params: + continue + + copy_param = copy_signature.parameters.get(name) + assert copy_param is not None, f"copy() signature is missing the {name} param" + + @pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12") + def test_copy_build_request(self, async_client: AsyncCourier) -> None: + options = FinalRequestOptions(method="get", url="/foo") + + def build_request(options: FinalRequestOptions) -> None: + client_copy = async_client.copy() + client_copy._build_request(options) + + # ensure that the machinery is warmed up before tracing starts. + build_request(options) + gc.collect() + + tracemalloc.start(1000) + + snapshot_before = tracemalloc.take_snapshot() + + ITERATIONS = 10 + for _ in range(ITERATIONS): + build_request(options) + + gc.collect() + snapshot_after = tracemalloc.take_snapshot() + + tracemalloc.stop() + + def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None: + if diff.count == 0: + # Avoid false positives by considering only leaks (i.e. allocations that persist). + return + + if diff.count % ITERATIONS != 0: + # Avoid false positives by considering only leaks that appear per iteration. + return + + for frame in diff.traceback: + if any( + frame.filename.endswith(fragment) + for fragment in [ + # to_raw_response_wrapper leaks through the @functools.wraps() decorator. + # + # removing the decorator fixes the leak for reasons we don't understand. + "courier/_legacy_response.py", + "courier/_response.py", + # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. + "courier/_compat.py", + # Standard library leaks we don't care about. + "/logging/__init__.py", + ] + ): + return + + leaks.append(diff) + + leaks: list[tracemalloc.StatisticDiff] = [] + for diff in snapshot_after.compare_to(snapshot_before, "traceback"): + add_leak(leaks, diff) + if leaks: + for leak in leaks: + print("MEMORY LEAK:", leak) + for frame in leak.traceback: + print(frame) + raise AssertionError() + + async def test_request_timeout(self, async_client: AsyncCourier) -> None: + request = async_client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + request = async_client._build_request( + FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0)) + ) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(100.0) + + async def test_client_timeout_option(self) -> None: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=httpx.Timeout(0) + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(0) + + await client.close() + + async def test_http_client_timeout_option(self) -> None: + # custom timeout given to the httpx client should be used + async with httpx.AsyncClient(timeout=None) as http_client: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(None) + + await client.close() + + # no timeout given to the httpx client should not use the httpx default + async with httpx.AsyncClient() as http_client: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + await client.close() + + # explicitly passing the default timeout currently results in it being ignored + async with httpx.AsyncClient(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT # our default + + await client.close() + + def test_invalid_http_client(self) -> None: + with pytest.raises(TypeError, match="Invalid `http_client` arg"): + with httpx.Client() as http_client: + AsyncCourier( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=cast(Any, http_client), + ) + + async def test_default_headers_option(self) -> None: + test_client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + request = test_client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "bar" + assert request.headers.get("x-stainless-lang") == "python" + + test_client2 = AsyncCourier( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + default_headers={ + "X-Foo": "stainless", + "X-Stainless-Lang": "my-overriding-header", + }, + ) + request = test_client2._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "stainless" + assert request.headers.get("x-stainless-lang") == "my-overriding-header" + + await test_client.close() + await test_client2.close() + + def test_validate_headers(self) -> None: + client = AsyncCourier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("Authorization") == f"Bearer {api_key}" + + with pytest.raises(CourierError): + with update_env(**{"COURIER_API_KEY": Omit()}): + client2 = AsyncCourier(base_url=base_url, api_key=None, _strict_response_validation=True) + _ = client2 + + async def test_default_query_option(self) -> None: + client = AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"} + ) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + url = httpx.URL(request.url) + assert dict(url.params) == {"query_param": "bar"} + + request = client._build_request( + FinalRequestOptions( + method="get", + url="/foo", + params={"foo": "baz", "query_param": "overridden"}, + ) + ) + url = httpx.URL(request.url) + assert dict(url.params) == {"foo": "baz", "query_param": "overridden"} + + await client.close() + + async def test_hardcoded_query_params_in_url(self, async_client: AsyncCourier) -> None: + request = async_client._build_request(FinalRequestOptions(method="get", url="/foo?beta=true")) + url = httpx.URL(request.url) + assert dict(url.params) == {"beta": "true"} + + request = async_client._build_request( + FinalRequestOptions( + method="get", + url="/foo?beta=true", + params={"limit": "10", "page": "abc"}, + ) + ) + url = httpx.URL(request.url) + assert dict(url.params) == {"beta": "true", "limit": "10", "page": "abc"} + + request = async_client._build_request( + FinalRequestOptions( + method="get", + url="/files/a%2Fb?beta=true", + params={"limit": "10"}, + ) + ) + assert request.url.raw_path == b"/files/a%2Fb?beta=true&limit=10" + + def test_request_extra_json(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": False} + + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"baz": False} + + # `extra_json` takes priority over `json_data` when keys clash + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar", "baz": True}, + extra_json={"baz": None}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": None} + + def test_request_extra_headers(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options(extra_headers={"X-Foo": "Foo"}), + ), + ) + assert request.headers.get("X-Foo") == "Foo" + + # `extra_headers` takes priority over `default_headers` when keys clash + request = client.with_options(default_headers={"X-Bar": "true"})._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_headers={"X-Bar": "false"}, + ), + ), + ) + assert request.headers.get("X-Bar") == "false" + + def test_request_extra_query(self, client: Courier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_query={"my_query_param": "Foo"}, + ), + ), + ) + params = dict(request.url.params) + assert params == {"my_query_param": "Foo"} + + # if both `query` and `extra_query` are given, they are merged + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"bar": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = dict(request.url.params) + assert params == {"bar": "1", "foo": "2"} + + # `extra_query` takes priority over `query` when keys clash + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"foo": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = dict(request.url.params) + assert params == {"foo": "2"} + + def test_multipart_repeating_array(self, async_client: AsyncCourier) -> None: + request = async_client._build_request( + FinalRequestOptions.construct( + method="post", + url="/foo", + headers={"Content-Type": "multipart/form-data; boundary=6b7ba517decee4a450543ea6ae821c82"}, + json_data={"array": ["foo", "bar"]}, + files=[("foo.txt", b"hello world")], + ) + ) + + assert request.read().split(b"\r\n") == [ + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"foo", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"bar", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="foo.txt"; filename="upload"', + b"Content-Type: application/octet-stream", + b"", + b"hello world", + b"--6b7ba517decee4a450543ea6ae821c82--", + b"", + ] + + @pytest.mark.respx(base_url=base_url) + async def test_binary_content_upload(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + respx_mock.post("/upload").mock(side_effect=mirror_request_content) + + file_content = b"Hello, this is a test file." + + response = await async_client.post( + "/upload", + content=file_content, + cast_to=httpx.Response, + options={"headers": {"Content-Type": "application/octet-stream"}}, + ) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == "application/octet-stream" + assert response.content == file_content + + async def test_binary_content_upload_with_asynciterator(self) -> None: + file_content = b"Hello, this is a test file." + counter = Counter() + iterator = _make_async_iterator([file_content], counter=counter) + + async def mock_handler(request: httpx.Request) -> httpx.Response: + assert counter.value == 0, "the request body should not have been read" + return httpx.Response(200, content=await request.aread()) + + async with AsyncCourier( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(transport=MockTransport(handler=mock_handler)), + ) as client: + response = await client.post( + "/upload", + content=iterator, + cast_to=httpx.Response, + options={"headers": {"Content-Type": "application/octet-stream"}}, + ) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == "application/octet-stream" + assert response.content == file_content + assert counter.value == 1 + + @pytest.mark.respx(base_url=base_url) + async def test_binary_content_upload_with_body_is_deprecated( + self, respx_mock: MockRouter, async_client: AsyncCourier + ) -> None: + respx_mock.post("/upload").mock(side_effect=mirror_request_content) + + file_content = b"Hello, this is a test file." + + with pytest.deprecated_call( + match="Passing raw bytes as `body` is deprecated and will be removed in a future version. Please pass raw bytes via the `content` parameter instead." + ): + response = await async_client.post( + "/upload", + body=file_content, + cast_to=httpx.Response, + options={"headers": {"Content-Type": "application/octet-stream"}}, + ) + + assert response.status_code == 200 + assert response.request.headers["Content-Type"] == "application/octet-stream" + assert response.content == file_content + + @pytest.mark.respx(base_url=base_url) + async def test_basic_union_response(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + class Model1(BaseModel): + name: str + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + @pytest.mark.respx(base_url=base_url) + async def test_union_response_different_types(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + """Union of objects with the same field name using a different type""" + + class Model1(BaseModel): + foo: int + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": 1})) + + response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model1) + assert response.foo == 1 + + @pytest.mark.respx(base_url=base_url) + async def test_non_application_json_content_type_for_json_data( + self, respx_mock: MockRouter, async_client: AsyncCourier + ) -> None: + """ + Response that sets Content-Type to something other than application/json but returns json data + """ + + class Model(BaseModel): + foo: int + + respx_mock.get("/foo").mock( + return_value=httpx.Response( + 200, + content=json.dumps({"foo": 2}), + headers={"Content-Type": "application/text"}, + ) + ) + + response = await async_client.get("/foo", cast_to=Model) + assert isinstance(response, Model) + assert response.foo == 2 + + async def test_base_url_setter(self) -> None: + client = AsyncCourier( + base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True + ) + assert client.base_url == "https://example.com/from_init/" + + client.base_url = "https://example.com/from_setter" # type: ignore[assignment] + + assert client.base_url == "https://example.com/from_setter/" + + await client.close() + + async def test_base_url_env(self) -> None: + with update_env(COURIER_BASE_URL="http://localhost:5000/from/env"): + client = AsyncCourier(api_key=api_key, _strict_response_validation=True) + assert client.base_url == "http://localhost:5000/from/env/" + + @pytest.mark.parametrize( + "client", + [ + AsyncCourier( + base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True + ), + AsyncCourier( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(), + ), + ], + ids=["standard", "custom http client"], + ) + async def test_base_url_trailing_slash(self, client: AsyncCourier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + await client.close() + + @pytest.mark.parametrize( + "client", + [ + AsyncCourier( + base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True + ), + AsyncCourier( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(), + ), + ], + ids=["standard", "custom http client"], + ) + async def test_base_url_no_trailing_slash(self, client: AsyncCourier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + await client.close() + + @pytest.mark.parametrize( + "client", + [ + AsyncCourier( + base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True + ), + AsyncCourier( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(), + ), + ], + ids=["standard", "custom http client"], + ) + async def test_absolute_request_url(self, client: AsyncCourier) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="https://myapi.com/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "https://myapi.com/foo" + await client.close() + + async def test_copied_client_does_not_close_http(self) -> None: + test_client = AsyncCourier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + assert not test_client.is_closed() + + copied = test_client.copy() + assert copied is not test_client + + del copied + + await asyncio.sleep(0.2) + assert not test_client.is_closed() + + async def test_client_context_manager(self) -> None: + test_client = AsyncCourier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + async with test_client as c2: + assert c2 is test_client + assert not c2.is_closed() + assert not test_client.is_closed() + assert test_client.is_closed() + + @pytest.mark.respx(base_url=base_url) + async def test_client_response_validation_error(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + class Model(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": {"invalid": True}})) + + with pytest.raises(APIResponseValidationError) as exc: + await async_client.get("/foo", cast_to=Model) + + assert isinstance(exc.value.__cause__, ValidationError) + + async def test_client_max_retries_validation(self) -> None: + with pytest.raises(TypeError, match=r"max_retries cannot be None"): + AsyncCourier( + base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=cast(Any, None) + ) + + @pytest.mark.respx(base_url=base_url) + async def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + name: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, text="my-custom-format")) + + strict_client = AsyncCourier(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + with pytest.raises(APIResponseValidationError): + await strict_client.get("/foo", cast_to=Model) + + non_strict_client = AsyncCourier(base_url=base_url, api_key=api_key, _strict_response_validation=False) + + response = await non_strict_client.get("/foo", cast_to=Model) + assert isinstance(response, str) # type: ignore[unreachable] + + await strict_client.close() + await non_strict_client.close() + + @pytest.mark.parametrize( + "remaining_retries,retry_after,timeout", + [ + [3, "20", 20], + [3, "0", 0.5], + [3, "-10", 0.5], + [3, "60", 60], + [3, "61", 0.5], + [3, "Fri, 29 Sep 2023 16:26:57 GMT", 20], + [3, "Fri, 29 Sep 2023 16:26:37 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:27:37 GMT", 60], + [3, "Fri, 29 Sep 2023 16:27:38 GMT", 0.5], + [3, "99999999999999999999999999999999999", 0.5], + [3, "Zun, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "", 0.5], + [2, "", 0.5 * 2.0], + [1, "", 0.5 * 4.0], + [-1100, "", 8], # test large number potentially overflowing + ], + ) + @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) + async def test_parse_retry_after_header( + self, remaining_retries: int, retry_after: str, timeout: float, async_client: AsyncCourier + ) -> None: + headers = httpx.Headers({"retry-after": retry_after}) + options = FinalRequestOptions(method="get", url="/foo", max_retries=3) + calculated = async_client._calculate_retry_timeout(remaining_retries, options, headers) + assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + async def test_retrying_timeout_errors_doesnt_leak( + self, respx_mock: MockRouter, async_client: AsyncCourier + ) -> None: + respx_mock.post("/send").mock(side_effect=httpx.TimeoutException("Test timeout error")) + + with pytest.raises(APITimeoutError): + await async_client.send.with_streaming_response.message(message={}).__aenter__() + + assert _get_open_connections(async_client) == 0 + + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + respx_mock.post("/send").mock(return_value=httpx.Response(500)) + + with pytest.raises(APIStatusError): + await async_client.send.with_streaming_response.message(message={}).__aenter__() + assert _get_open_connections(async_client) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + @pytest.mark.parametrize("failure_mode", ["status", "exception"]) + async def test_retries_taken( + self, + async_client: AsyncCourier, + failures_before_success: int, + failure_mode: Literal["status", "exception"], + respx_mock: MockRouter, + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + if failure_mode == "exception": + raise RuntimeError("oops") + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/send").mock(side_effect=retry_handler) + + response = await client.send.with_raw_response.message(message={}) + + assert response.retries_taken == failures_before_success + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + async def test_omit_retry_count_header( + self, async_client: AsyncCourier, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/send").mock(side_effect=retry_handler) + + response = await client.send.with_raw_response.message( + message={}, extra_headers={"x-stainless-retry-count": Omit()} + ) + + assert len(response.http_request.headers.get_list("x-stainless-retry-count")) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("courier._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + async def test_overwrite_retry_count_header( + self, async_client: AsyncCourier, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/send").mock(side_effect=retry_handler) + + response = await client.send.with_raw_response.message( + message={}, extra_headers={"x-stainless-retry-count": "42"} + ) + + assert response.http_request.headers.get("x-stainless-retry-count") == "42" + + async def test_get_platform(self) -> None: + platform = await asyncify(get_platform)() + assert isinstance(platform, (str, OtherPlatform)) + + async def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None: + # Test that the proxy environment variables are set correctly + monkeypatch.setenv("HTTPS_PROXY", "https://example.org") + # Delete in case our environment has any proxy env vars set + monkeypatch.delenv("HTTP_PROXY", raising=False) + monkeypatch.delenv("ALL_PROXY", raising=False) + monkeypatch.delenv("NO_PROXY", raising=False) + monkeypatch.delenv("http_proxy", raising=False) + monkeypatch.delenv("https_proxy", raising=False) + monkeypatch.delenv("all_proxy", raising=False) + monkeypatch.delenv("no_proxy", raising=False) + + client = DefaultAsyncHttpxClient() + + mounts = tuple(client._mounts.items()) + assert len(mounts) == 1 + assert mounts[0][0].pattern == "https://" + + @pytest.mark.filterwarnings("ignore:.*deprecated.*:DeprecationWarning") + async def test_default_client_creation(self) -> None: + # Ensure that the client can be initialized without any exceptions + DefaultAsyncHttpxClient( + verify=True, + cert=None, + trust_env=True, + http1=True, + http2=False, + limits=httpx.Limits(max_connections=100, max_keepalive_connections=20), + ) + + @pytest.mark.respx(base_url=base_url) + async def test_follow_redirects(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + # Test that the default follow_redirects=True allows following redirects + respx_mock.post("/redirect").mock( + return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"}) + ) + respx_mock.get("/redirected").mock(return_value=httpx.Response(200, json={"status": "ok"})) + + response = await async_client.post("/redirect", body={"key": "value"}, cast_to=httpx.Response) + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + @pytest.mark.respx(base_url=base_url) + async def test_follow_redirects_disabled(self, respx_mock: MockRouter, async_client: AsyncCourier) -> None: + # Test that follow_redirects=False prevents following redirects + respx_mock.post("/redirect").mock( + return_value=httpx.Response(302, headers={"Location": f"{base_url}/redirected"}) + ) + + with pytest.raises(APIStatusError) as exc_info: + await async_client.post( + "/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx.Response + ) + + assert exc_info.value.response.status_code == 302 + assert exc_info.value.response.headers["Location"] == f"{base_url}/redirected" diff --git a/tests/test_extract_files.py b/tests/test_extract_files.py new file mode 100644 index 00000000..21892d26 --- /dev/null +++ b/tests/test_extract_files.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from typing import Sequence + +import pytest + +from courier._types import FileTypes, ArrayFormat +from courier._utils import extract_files + + +def test_removes_files_from_input() -> None: + query = {"foo": "bar"} + assert extract_files(query, paths=[]) == [] + assert query == {"foo": "bar"} + + query2 = {"foo": b"Bar", "hello": "world"} + assert extract_files(query2, paths=[["foo"]]) == [("foo", b"Bar")] + assert query2 == {"hello": "world"} + + query3 = {"foo": {"foo": {"bar": b"Bar"}}, "hello": "world"} + assert extract_files(query3, paths=[["foo", "foo", "bar"]]) == [("foo[foo][bar]", b"Bar")] + assert query3 == {"foo": {"foo": {}}, "hello": "world"} + + query4 = {"foo": {"bar": b"Bar", "baz": "foo"}, "hello": "world"} + assert extract_files(query4, paths=[["foo", "bar"]]) == [("foo[bar]", b"Bar")] + assert query4 == {"hello": "world", "foo": {"baz": "foo"}} + + +def test_multiple_files() -> None: + query = {"documents": [{"file": b"My first file"}, {"file": b"My second file"}]} + assert extract_files(query, paths=[["documents", "", "file"]]) == [ + ("documents[][file]", b"My first file"), + ("documents[][file]", b"My second file"), + ] + assert query == {"documents": [{}, {}]} + + +def test_top_level_file_array() -> None: + query = {"files": [b"file one", b"file two"], "title": "hello"} + assert extract_files(query, paths=[["files", ""]]) == [("files[]", b"file one"), ("files[]", b"file two")] + assert query == {"title": "hello"} + + +@pytest.mark.parametrize( + "query,paths,expected", + [ + [ + {"foo": {"bar": "baz"}}, + [["foo", "", "bar"]], + [], + ], + [ + {"foo": ["bar", "baz"]}, + [["foo", "bar"]], + [], + ], + [ + {"foo": {"bar": "baz"}}, + [["foo", "foo"]], + [], + ], + ], + ids=["dict expecting array", "array expecting dict", "unknown keys"], +) +def test_ignores_incorrect_paths( + query: dict[str, object], + paths: Sequence[Sequence[str]], + expected: list[tuple[str, FileTypes]], +) -> None: + assert extract_files(query, paths=paths) == expected + + +@pytest.mark.parametrize( + "array_format,expected_top_level,expected_nested", + [ + ("brackets", [("files[]", b"a"), ("files[]", b"b")], [("items[][file]", b"a"), ("items[][file]", b"b")]), + ("repeat", [("files", b"a"), ("files", b"b")], [("items[file]", b"a"), ("items[file]", b"b")]), + ("comma", [("files", b"a"), ("files", b"b")], [("items[file]", b"a"), ("items[file]", b"b")]), + ("indices", [("files[0]", b"a"), ("files[1]", b"b")], [("items[0][file]", b"a"), ("items[1][file]", b"b")]), + ], +) +def test_array_format_controls_file_field_names( + array_format: ArrayFormat, + expected_top_level: list[tuple[str, FileTypes]], + expected_nested: list[tuple[str, FileTypes]], +) -> None: + top_level = {"files": [b"a", b"b"]} + assert extract_files(top_level, paths=[["files", ""]], array_format=array_format) == expected_top_level + + nested = {"items": [{"file": b"a"}, {"file": b"b"}]} + assert extract_files(nested, paths=[["items", "", "file"]], array_format=array_format) == expected_nested diff --git a/tests/test_files.py b/tests/test_files.py new file mode 100644 index 00000000..0a711de9 --- /dev/null +++ b/tests/test_files.py @@ -0,0 +1,148 @@ +from pathlib import Path + +import anyio +import pytest +from dirty_equals import IsDict, IsList, IsBytes, IsTuple + +from courier._files import to_httpx_files, deepcopy_with_paths, async_to_httpx_files +from courier._utils import extract_files + +readme_path = Path(__file__).parent.parent.joinpath("README.md") + + +def test_pathlib_includes_file_name() -> None: + result = to_httpx_files({"file": readme_path}) + print(result) + assert result == IsDict({"file": IsTuple("README.md", IsBytes())}) + + +def test_tuple_input() -> None: + result = to_httpx_files([("file", readme_path)]) + print(result) + assert result == IsList(IsTuple("file", IsTuple("README.md", IsBytes()))) + + +@pytest.mark.asyncio +async def test_async_pathlib_includes_file_name() -> None: + result = await async_to_httpx_files({"file": readme_path}) + print(result) + assert result == IsDict({"file": IsTuple("README.md", IsBytes())}) + + +@pytest.mark.asyncio +async def test_async_supports_anyio_path() -> None: + result = await async_to_httpx_files({"file": anyio.Path(readme_path)}) + print(result) + assert result == IsDict({"file": IsTuple("README.md", IsBytes())}) + + +@pytest.mark.asyncio +async def test_async_tuple_input() -> None: + result = await async_to_httpx_files([("file", readme_path)]) + print(result) + assert result == IsList(IsTuple("file", IsTuple("README.md", IsBytes()))) + + +def test_string_not_allowed() -> None: + with pytest.raises(TypeError, match="Expected file types input to be a FileContent type or to be a tuple"): + to_httpx_files( + { + "file": "foo", # type: ignore + } + ) + + +def assert_different_identities(obj1: object, obj2: object) -> None: + assert obj1 == obj2 + assert obj1 is not obj2 + + +class TestDeepcopyWithPaths: + def test_copies_top_level_dict(self) -> None: + original = {"file": b"data", "other": "value"} + result = deepcopy_with_paths(original, [["file"]]) + assert_different_identities(result, original) + + def test_file_value_is_same_reference(self) -> None: + file_bytes = b"contents" + original = {"file": file_bytes} + result = deepcopy_with_paths(original, [["file"]]) + assert_different_identities(result, original) + assert result["file"] is file_bytes + + def test_list_popped_wholesale(self) -> None: + files = [b"f1", b"f2"] + original = {"files": files, "title": "t"} + result = deepcopy_with_paths(original, [["files", ""]]) + assert_different_identities(result, original) + result_files = result["files"] + assert isinstance(result_files, list) + assert_different_identities(result_files, files) + + def test_nested_array_path_copies_list_and_elements(self) -> None: + elem1 = {"file": b"f1", "extra": 1} + elem2 = {"file": b"f2", "extra": 2} + original = {"items": [elem1, elem2]} + result = deepcopy_with_paths(original, [["items", "", "file"]]) + assert_different_identities(result, original) + result_items = result["items"] + assert isinstance(result_items, list) + assert_different_identities(result_items, original["items"]) + assert_different_identities(result_items[0], elem1) + assert_different_identities(result_items[1], elem2) + + def test_empty_paths_returns_same_object(self) -> None: + original = {"foo": "bar"} + result = deepcopy_with_paths(original, []) + assert result is original + + def test_multiple_paths(self) -> None: + f1 = b"file1" + f2 = b"file2" + original = {"a": f1, "b": f2, "c": "unchanged"} + result = deepcopy_with_paths(original, [["a"], ["b"]]) + assert_different_identities(result, original) + assert result["a"] is f1 + assert result["b"] is f2 + assert result["c"] is original["c"] + + def test_extract_files_does_not_mutate_original_top_level(self) -> None: + file_bytes = b"contents" + original = {"file": file_bytes, "other": "value"} + + copied = deepcopy_with_paths(original, [["file"]]) + extracted = extract_files(copied, paths=[["file"]]) + + assert extracted == [("file", file_bytes)] + assert original == {"file": file_bytes, "other": "value"} + assert copied == {"other": "value"} + + def test_extract_files_does_not_mutate_original_nested_array_path(self) -> None: + file1 = b"f1" + file2 = b"f2" + original = { + "items": [ + {"file": file1, "extra": 1}, + {"file": file2, "extra": 2}, + ], + "title": "example", + } + + copied = deepcopy_with_paths(original, [["items", "", "file"]]) + extracted = extract_files(copied, paths=[["items", "", "file"]]) + + assert [entry for _, entry in extracted] == [file1, file2] + assert original == { + "items": [ + {"file": file1, "extra": 1}, + {"file": file2, "extra": 2}, + ], + "title": "example", + } + assert copied == { + "items": [ + {"extra": 1}, + {"extra": 2}, + ], + "title": "example", + } diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 00000000..61638ab8 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,1017 @@ +import json +from typing import TYPE_CHECKING, Any, Dict, List, Union, Iterable, Optional, cast +from datetime import datetime, timezone +from collections import deque +from typing_extensions import Literal, Annotated, TypedDict, TypeAliasType + +import pytest +import pydantic +from pydantic import Field + +from courier._utils import PropertyInfo +from courier._compat import PYDANTIC_V1, parse_obj, model_dump, model_json +from courier._models import DISCRIMINATOR_CACHE, BaseModel, EagerIterable, construct_type + + +class BasicModel(BaseModel): + foo: str + + +@pytest.mark.parametrize("value", ["hello", 1], ids=["correct type", "mismatched"]) +def test_basic(value: object) -> None: + m = BasicModel.construct(foo=value) + assert m.foo == value + + +def test_directly_nested_model() -> None: + class NestedModel(BaseModel): + nested: BasicModel + + m = NestedModel.construct(nested={"foo": "Foo!"}) + assert m.nested.foo == "Foo!" + + # mismatched types + m = NestedModel.construct(nested="hello!") + assert cast(Any, m.nested) == "hello!" + + +def test_optional_nested_model() -> None: + class NestedModel(BaseModel): + nested: Optional[BasicModel] + + m1 = NestedModel.construct(nested=None) + assert m1.nested is None + + m2 = NestedModel.construct(nested={"foo": "bar"}) + assert m2.nested is not None + assert m2.nested.foo == "bar" + + # mismatched types + m3 = NestedModel.construct(nested={"foo"}) + assert isinstance(cast(Any, m3.nested), set) + assert cast(Any, m3.nested) == {"foo"} + + +def test_list_nested_model() -> None: + class NestedModel(BaseModel): + nested: List[BasicModel] + + m = NestedModel.construct(nested=[{"foo": "bar"}, {"foo": "2"}]) + assert m.nested is not None + assert isinstance(m.nested, list) + assert len(m.nested) == 2 + assert m.nested[0].foo == "bar" + assert m.nested[1].foo == "2" + + # mismatched types + m = NestedModel.construct(nested=True) + assert cast(Any, m.nested) is True + + m = NestedModel.construct(nested=[False]) + assert cast(Any, m.nested) == [False] + + +def test_optional_list_nested_model() -> None: + class NestedModel(BaseModel): + nested: Optional[List[BasicModel]] + + m1 = NestedModel.construct(nested=[{"foo": "bar"}, {"foo": "2"}]) + assert m1.nested is not None + assert isinstance(m1.nested, list) + assert len(m1.nested) == 2 + assert m1.nested[0].foo == "bar" + assert m1.nested[1].foo == "2" + + m2 = NestedModel.construct(nested=None) + assert m2.nested is None + + # mismatched types + m3 = NestedModel.construct(nested={1}) + assert cast(Any, m3.nested) == {1} + + m4 = NestedModel.construct(nested=[False]) + assert cast(Any, m4.nested) == [False] + + +def test_list_optional_items_nested_model() -> None: + class NestedModel(BaseModel): + nested: List[Optional[BasicModel]] + + m = NestedModel.construct(nested=[None, {"foo": "bar"}]) + assert m.nested is not None + assert isinstance(m.nested, list) + assert len(m.nested) == 2 + assert m.nested[0] is None + assert m.nested[1] is not None + assert m.nested[1].foo == "bar" + + # mismatched types + m3 = NestedModel.construct(nested="foo") + assert cast(Any, m3.nested) == "foo" + + m4 = NestedModel.construct(nested=[False]) + assert cast(Any, m4.nested) == [False] + + +def test_list_mismatched_type() -> None: + class NestedModel(BaseModel): + nested: List[str] + + m = NestedModel.construct(nested=False) + assert cast(Any, m.nested) is False + + +def test_raw_dictionary() -> None: + class NestedModel(BaseModel): + nested: Dict[str, str] + + m = NestedModel.construct(nested={"hello": "world"}) + assert m.nested == {"hello": "world"} + + # mismatched types + m = NestedModel.construct(nested=False) + assert cast(Any, m.nested) is False + + +def test_nested_dictionary_model() -> None: + class NestedModel(BaseModel): + nested: Dict[str, BasicModel] + + m = NestedModel.construct(nested={"hello": {"foo": "bar"}}) + assert isinstance(m.nested, dict) + assert m.nested["hello"].foo == "bar" + + # mismatched types + m = NestedModel.construct(nested={"hello": False}) + assert cast(Any, m.nested["hello"]) is False + + +def test_unknown_fields() -> None: + m1 = BasicModel.construct(foo="foo", unknown=1) + assert m1.foo == "foo" + assert cast(Any, m1).unknown == 1 + + m2 = BasicModel.construct(foo="foo", unknown={"foo_bar": True}) + assert m2.foo == "foo" + assert cast(Any, m2).unknown == {"foo_bar": True} + + assert model_dump(m2) == {"foo": "foo", "unknown": {"foo_bar": True}} + + +def test_strict_validation_unknown_fields() -> None: + class Model(BaseModel): + foo: str + + model = parse_obj(Model, dict(foo="hello!", user="Robert")) + assert model.foo == "hello!" + assert cast(Any, model).user == "Robert" + + assert model_dump(model) == {"foo": "hello!", "user": "Robert"} + + +def test_aliases() -> None: + class Model(BaseModel): + my_field: int = Field(alias="myField") + + m = Model.construct(myField=1) + assert m.my_field == 1 + + # mismatched types + m = Model.construct(myField={"hello": False}) + assert cast(Any, m.my_field) == {"hello": False} + + +def test_repr() -> None: + model = BasicModel(foo="bar") + assert str(model) == "BasicModel(foo='bar')" + assert repr(model) == "BasicModel(foo='bar')" + + +def test_repr_nested_model() -> None: + class Child(BaseModel): + name: str + age: int + + class Parent(BaseModel): + name: str + child: Child + + model = Parent(name="Robert", child=Child(name="Foo", age=5)) + assert str(model) == "Parent(name='Robert', child=Child(name='Foo', age=5))" + assert repr(model) == "Parent(name='Robert', child=Child(name='Foo', age=5))" + + +def test_optional_list() -> None: + class Submodel(BaseModel): + name: str + + class Model(BaseModel): + items: Optional[List[Submodel]] + + m = Model.construct(items=None) + assert m.items is None + + m = Model.construct(items=[]) + assert m.items == [] + + m = Model.construct(items=[{"name": "Robert"}]) + assert m.items is not None + assert len(m.items) == 1 + assert m.items[0].name == "Robert" + + +def test_nested_union_of_models() -> None: + class Submodel1(BaseModel): + bar: bool + + class Submodel2(BaseModel): + thing: str + + class Model(BaseModel): + foo: Union[Submodel1, Submodel2] + + m = Model.construct(foo={"thing": "hello"}) + assert isinstance(m.foo, Submodel2) + assert m.foo.thing == "hello" + + +def test_nested_union_of_mixed_types() -> None: + class Submodel1(BaseModel): + bar: bool + + class Model(BaseModel): + foo: Union[Submodel1, Literal[True], Literal["CARD_HOLDER"]] + + m = Model.construct(foo=True) + assert m.foo is True + + m = Model.construct(foo="CARD_HOLDER") + assert m.foo == "CARD_HOLDER" + + m = Model.construct(foo={"bar": False}) + assert isinstance(m.foo, Submodel1) + assert m.foo.bar is False + + +def test_nested_union_multiple_variants() -> None: + class Submodel1(BaseModel): + bar: bool + + class Submodel2(BaseModel): + thing: str + + class Submodel3(BaseModel): + foo: int + + class Model(BaseModel): + foo: Union[Submodel1, Submodel2, None, Submodel3] + + m = Model.construct(foo={"thing": "hello"}) + assert isinstance(m.foo, Submodel2) + assert m.foo.thing == "hello" + + m = Model.construct(foo=None) + assert m.foo is None + + m = Model.construct() + assert m.foo is None + + m = Model.construct(foo={"foo": "1"}) + assert isinstance(m.foo, Submodel3) + assert m.foo.foo == 1 + + +def test_nested_union_invalid_data() -> None: + class Submodel1(BaseModel): + level: int + + class Submodel2(BaseModel): + name: str + + class Model(BaseModel): + foo: Union[Submodel1, Submodel2] + + m = Model.construct(foo=True) + assert cast(bool, m.foo) is True + + m = Model.construct(foo={"name": 3}) + if PYDANTIC_V1: + assert isinstance(m.foo, Submodel2) + assert m.foo.name == "3" + else: + assert isinstance(m.foo, Submodel1) + assert m.foo.name == 3 # type: ignore + + +def test_list_of_unions() -> None: + class Submodel1(BaseModel): + level: int + + class Submodel2(BaseModel): + name: str + + class Model(BaseModel): + items: List[Union[Submodel1, Submodel2]] + + m = Model.construct(items=[{"level": 1}, {"name": "Robert"}]) + assert len(m.items) == 2 + assert isinstance(m.items[0], Submodel1) + assert m.items[0].level == 1 + assert isinstance(m.items[1], Submodel2) + assert m.items[1].name == "Robert" + + m = Model.construct(items=[{"level": -1}, 156]) + assert len(m.items) == 2 + assert isinstance(m.items[0], Submodel1) + assert m.items[0].level == -1 + assert cast(Any, m.items[1]) == 156 + + +def test_union_of_lists() -> None: + class SubModel1(BaseModel): + level: int + + class SubModel2(BaseModel): + name: str + + class Model(BaseModel): + items: Union[List[SubModel1], List[SubModel2]] + + # with one valid entry + m = Model.construct(items=[{"name": "Robert"}]) + assert len(m.items) == 1 + assert isinstance(m.items[0], SubModel2) + assert m.items[0].name == "Robert" + + # with two entries pointing to different types + m = Model.construct(items=[{"level": 1}, {"name": "Robert"}]) + assert len(m.items) == 2 + assert isinstance(m.items[0], SubModel1) + assert m.items[0].level == 1 + assert isinstance(m.items[1], SubModel1) + assert cast(Any, m.items[1]).name == "Robert" + + # with two entries pointing to *completely* different types + m = Model.construct(items=[{"level": -1}, 156]) + assert len(m.items) == 2 + assert isinstance(m.items[0], SubModel1) + assert m.items[0].level == -1 + assert cast(Any, m.items[1]) == 156 + + +def test_dict_of_union() -> None: + class SubModel1(BaseModel): + name: str + + class SubModel2(BaseModel): + foo: str + + class Model(BaseModel): + data: Dict[str, Union[SubModel1, SubModel2]] + + m = Model.construct(data={"hello": {"name": "there"}, "foo": {"foo": "bar"}}) + assert len(list(m.data.keys())) == 2 + assert isinstance(m.data["hello"], SubModel1) + assert m.data["hello"].name == "there" + assert isinstance(m.data["foo"], SubModel2) + assert m.data["foo"].foo == "bar" + + # TODO: test mismatched type + + +def test_double_nested_union() -> None: + class SubModel1(BaseModel): + name: str + + class SubModel2(BaseModel): + bar: str + + class Model(BaseModel): + data: Dict[str, List[Union[SubModel1, SubModel2]]] + + m = Model.construct(data={"foo": [{"bar": "baz"}, {"name": "Robert"}]}) + assert len(m.data["foo"]) == 2 + + entry1 = m.data["foo"][0] + assert isinstance(entry1, SubModel2) + assert entry1.bar == "baz" + + entry2 = m.data["foo"][1] + assert isinstance(entry2, SubModel1) + assert entry2.name == "Robert" + + # TODO: test mismatched type + + +def test_union_of_dict() -> None: + class SubModel1(BaseModel): + name: str + + class SubModel2(BaseModel): + foo: str + + class Model(BaseModel): + data: Union[Dict[str, SubModel1], Dict[str, SubModel2]] + + m = Model.construct(data={"hello": {"name": "there"}, "foo": {"foo": "bar"}}) + assert len(list(m.data.keys())) == 2 + assert isinstance(m.data["hello"], SubModel1) + assert m.data["hello"].name == "there" + assert isinstance(m.data["foo"], SubModel1) + assert cast(Any, m.data["foo"]).foo == "bar" + + +def test_iso8601_datetime() -> None: + class Model(BaseModel): + created_at: datetime + + expected = datetime(2019, 12, 27, 18, 11, 19, 117000, tzinfo=timezone.utc) + + if PYDANTIC_V1: + expected_json = '{"created_at": "2019-12-27T18:11:19.117000+00:00"}' + else: + expected_json = '{"created_at":"2019-12-27T18:11:19.117000Z"}' + + model = Model.construct(created_at="2019-12-27T18:11:19.117Z") + assert model.created_at == expected + assert model_json(model) == expected_json + + model = parse_obj(Model, dict(created_at="2019-12-27T18:11:19.117Z")) + assert model.created_at == expected + assert model_json(model) == expected_json + + +def test_does_not_coerce_int() -> None: + class Model(BaseModel): + bar: int + + assert Model.construct(bar=1).bar == 1 + assert Model.construct(bar=10.9).bar == 10.9 + assert Model.construct(bar="19").bar == "19" # type: ignore[comparison-overlap] + assert Model.construct(bar=False).bar is False + + +def test_int_to_float_safe_conversion() -> None: + class Model(BaseModel): + float_field: float + + m = Model.construct(float_field=10) + assert m.float_field == 10.0 + assert isinstance(m.float_field, float) + + m = Model.construct(float_field=10.12) + assert m.float_field == 10.12 + assert isinstance(m.float_field, float) + + # number too big + m = Model.construct(float_field=2**53 + 1) + assert m.float_field == 2**53 + 1 + assert isinstance(m.float_field, int) + + +def test_deprecated_alias() -> None: + class Model(BaseModel): + resource_id: str = Field(alias="model_id") + + @property + def model_id(self) -> str: + return self.resource_id + + m = Model.construct(model_id="id") + assert m.model_id == "id" + assert m.resource_id == "id" + assert m.resource_id is m.model_id + + m = parse_obj(Model, {"model_id": "id"}) + assert m.model_id == "id" + assert m.resource_id == "id" + assert m.resource_id is m.model_id + + +def test_omitted_fields() -> None: + class Model(BaseModel): + resource_id: Optional[str] = None + + m = Model.construct() + assert m.resource_id is None + assert "resource_id" not in m.model_fields_set + + m = Model.construct(resource_id=None) + assert m.resource_id is None + assert "resource_id" in m.model_fields_set + + m = Model.construct(resource_id="foo") + assert m.resource_id == "foo" + assert "resource_id" in m.model_fields_set + + +def test_to_dict() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert m.to_dict() == {"FOO": "hello"} + assert m.to_dict(use_api_names=False) == {"foo": "hello"} + + m2 = Model() + assert m2.to_dict() == {} + assert m2.to_dict(exclude_unset=False) == {"FOO": None} + assert m2.to_dict(exclude_unset=False, exclude_none=True) == {} + assert m2.to_dict(exclude_unset=False, exclude_defaults=True) == {} + + m3 = Model(FOO=None) + assert m3.to_dict() == {"FOO": None} + assert m3.to_dict(exclude_none=True) == {} + assert m3.to_dict(exclude_defaults=True) == {} + + class Model2(BaseModel): + created_at: datetime + + time_str = "2024-03-21T11:39:01.275859" + m4 = Model2.construct(created_at=time_str) + assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)} + assert m4.to_dict(mode="json") == {"created_at": time_str} + + if PYDANTIC_V1: + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.to_dict(warnings=False) + + +def test_forwards_compat_model_dump_method() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert m.model_dump() == {"foo": "hello"} + assert m.model_dump(include={"bar"}) == {} + assert m.model_dump(exclude={"foo"}) == {} + assert m.model_dump(by_alias=True) == {"FOO": "hello"} + + m2 = Model() + assert m2.model_dump() == {"foo": None} + assert m2.model_dump(exclude_unset=True) == {} + assert m2.model_dump(exclude_none=True) == {} + assert m2.model_dump(exclude_defaults=True) == {} + + m3 = Model(FOO=None) + assert m3.model_dump() == {"foo": None} + assert m3.model_dump(exclude_none=True) == {} + + if PYDANTIC_V1: + with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): + m.model_dump(round_trip=True) + + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.model_dump(warnings=False) + + +def test_compat_method_no_error_for_warnings() -> None: + class Model(BaseModel): + foo: Optional[str] + + m = Model(foo="hello") + assert isinstance(model_dump(m, warnings=False), dict) + + +def test_to_json() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert json.loads(m.to_json()) == {"FOO": "hello"} + assert json.loads(m.to_json(use_api_names=False)) == {"foo": "hello"} + + if PYDANTIC_V1: + assert m.to_json(indent=None) == '{"FOO": "hello"}' + else: + assert m.to_json(indent=None) == '{"FOO":"hello"}' + + m2 = Model() + assert json.loads(m2.to_json()) == {} + assert json.loads(m2.to_json(exclude_unset=False)) == {"FOO": None} + assert json.loads(m2.to_json(exclude_unset=False, exclude_none=True)) == {} + assert json.loads(m2.to_json(exclude_unset=False, exclude_defaults=True)) == {} + + m3 = Model(FOO=None) + assert json.loads(m3.to_json()) == {"FOO": None} + assert json.loads(m3.to_json(exclude_none=True)) == {} + + if PYDANTIC_V1: + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.to_json(warnings=False) + + +def test_forwards_compat_model_dump_json_method() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert json.loads(m.model_dump_json()) == {"foo": "hello"} + assert json.loads(m.model_dump_json(include={"bar"})) == {} + assert json.loads(m.model_dump_json(include={"foo"})) == {"foo": "hello"} + assert json.loads(m.model_dump_json(by_alias=True)) == {"FOO": "hello"} + + assert m.model_dump_json(indent=2) == '{\n "foo": "hello"\n}' + + m2 = Model() + assert json.loads(m2.model_dump_json()) == {"foo": None} + assert json.loads(m2.model_dump_json(exclude_unset=True)) == {} + assert json.loads(m2.model_dump_json(exclude_none=True)) == {} + assert json.loads(m2.model_dump_json(exclude_defaults=True)) == {} + + m3 = Model(FOO=None) + assert json.loads(m3.model_dump_json()) == {"foo": None} + assert json.loads(m3.model_dump_json(exclude_none=True)) == {} + + if PYDANTIC_V1: + with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): + m.model_dump_json(round_trip=True) + + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.model_dump_json(warnings=False) + + +def test_type_compat() -> None: + # our model type can be assigned to Pydantic's model type + + def takes_pydantic(model: pydantic.BaseModel) -> None: # noqa: ARG001 + ... + + class OurModel(BaseModel): + foo: Optional[str] = None + + takes_pydantic(OurModel()) + + +def test_annotated_types() -> None: + class Model(BaseModel): + value: str + + m = construct_type( + value={"value": "foo"}, + type_=cast(Any, Annotated[Model, "random metadata"]), + ) + assert isinstance(m, Model) + assert m.value == "foo" + + +def test_discriminated_unions_invalid_data() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + m = construct_type( + value={"type": "b", "data": "foo"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + m = construct_type( + value={"type": "a", "data": 100}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, A) + assert m.type == "a" + if PYDANTIC_V1: + # pydantic v1 automatically converts inputs to strings + # if the expected type is a str + assert m.data == "100" + else: + assert m.data == 100 # type: ignore[comparison-overlap] + + +def test_discriminated_unions_unknown_variant() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + m = construct_type( + value={"type": "c", "data": None, "new_thing": "bar"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + + # just chooses the first variant + assert isinstance(m, A) + assert m.type == "c" # type: ignore[comparison-overlap] + assert m.data == None # type: ignore[unreachable] + assert m.new_thing == "bar" + + +def test_discriminated_unions_invalid_data_nested_unions() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + class C(BaseModel): + type: Literal["c"] + + data: bool + + m = construct_type( + value={"type": "b", "data": "foo"}, + type_=cast(Any, Annotated[Union[Union[A, B], C], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + m = construct_type( + value={"type": "c", "data": "foo"}, + type_=cast(Any, Annotated[Union[Union[A, B], C], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, C) + assert m.type == "c" + assert m.data == "foo" # type: ignore[comparison-overlap] + + +def test_discriminated_unions_with_aliases_invalid_data() -> None: + class A(BaseModel): + foo_type: Literal["a"] = Field(alias="type") + + data: str + + class B(BaseModel): + foo_type: Literal["b"] = Field(alias="type") + + data: int + + m = construct_type( + value={"type": "b", "data": "foo"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="foo_type")]), + ) + assert isinstance(m, B) + assert m.foo_type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + m = construct_type( + value={"type": "a", "data": 100}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="foo_type")]), + ) + assert isinstance(m, A) + assert m.foo_type == "a" + if PYDANTIC_V1: + # pydantic v1 automatically converts inputs to strings + # if the expected type is a str + assert m.data == "100" + else: + assert m.data == 100 # type: ignore[comparison-overlap] + + +def test_discriminated_unions_overlapping_discriminators_invalid_data() -> None: + class A(BaseModel): + type: Literal["a"] + + data: bool + + class B(BaseModel): + type: Literal["a"] + + data: int + + m = construct_type( + value={"type": "a", "data": "foo"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, B) + assert m.type == "a" + assert m.data == "foo" # type: ignore[comparison-overlap] + + +def test_discriminated_unions_invalid_data_uses_cache() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + UnionType = cast(Any, Union[A, B]) + + assert not DISCRIMINATOR_CACHE.get(UnionType) + + m = construct_type( + value={"type": "b", "data": "foo"}, type_=cast(Any, Annotated[UnionType, PropertyInfo(discriminator="type")]) + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + discriminator = DISCRIMINATOR_CACHE.get(UnionType) + assert discriminator is not None + + m = construct_type( + value={"type": "b", "data": "foo"}, type_=cast(Any, Annotated[UnionType, PropertyInfo(discriminator="type")]) + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + # if the discriminator details object stays the same between invocations then + # we hit the cache + assert DISCRIMINATOR_CACHE.get(UnionType) is discriminator + + +@pytest.mark.skipif(PYDANTIC_V1, reason="TypeAliasType is not supported in Pydantic v1") +def test_type_alias_type() -> None: + Alias = TypeAliasType("Alias", str) # pyright: ignore + + class Model(BaseModel): + alias: Alias + union: Union[int, Alias] + + m = construct_type(value={"alias": "foo", "union": "bar"}, type_=Model) + assert isinstance(m, Model) + assert isinstance(m.alias, str) + assert m.alias == "foo" + assert isinstance(m.union, str) + assert m.union == "bar" + + +@pytest.mark.skipif(PYDANTIC_V1, reason="TypeAliasType is not supported in Pydantic v1") +def test_field_named_cls() -> None: + class Model(BaseModel): + cls: str + + m = construct_type(value={"cls": "foo"}, type_=Model) + assert isinstance(m, Model) + assert isinstance(m.cls, str) + + +def test_discriminated_union_case() -> None: + class A(BaseModel): + type: Literal["a"] + + data: bool + + class B(BaseModel): + type: Literal["b"] + + data: List[Union[A, object]] + + class ModelA(BaseModel): + type: Literal["modelA"] + + data: int + + class ModelB(BaseModel): + type: Literal["modelB"] + + required: str + + data: Union[A, B] + + # when constructing ModelA | ModelB, value data doesn't match ModelB exactly - missing `required` + m = construct_type( + value={"type": "modelB", "data": {"type": "a", "data": True}}, + type_=cast(Any, Annotated[Union[ModelA, ModelB], PropertyInfo(discriminator="type")]), + ) + + assert isinstance(m, ModelB) + + +def test_nested_discriminated_union() -> None: + class InnerType1(BaseModel): + type: Literal["type_1"] + + class InnerModel(BaseModel): + inner_value: str + + class InnerType2(BaseModel): + type: Literal["type_2"] + some_inner_model: InnerModel + + class Type1(BaseModel): + base_type: Literal["base_type_1"] + value: Annotated[ + Union[ + InnerType1, + InnerType2, + ], + PropertyInfo(discriminator="type"), + ] + + class Type2(BaseModel): + base_type: Literal["base_type_2"] + + T = Annotated[ + Union[ + Type1, + Type2, + ], + PropertyInfo(discriminator="base_type"), + ] + + model = construct_type( + type_=T, + value={ + "base_type": "base_type_1", + "value": { + "type": "type_2", + }, + }, + ) + assert isinstance(model, Type1) + assert isinstance(model.value, InnerType2) + + +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2 for now") +def test_extra_properties() -> None: + class Item(BaseModel): + prop: int + + class Model(BaseModel): + __pydantic_extra__: Dict[str, Item] = Field(init=False) # pyright: ignore[reportIncompatibleVariableOverride] + + other: str + + if TYPE_CHECKING: + + def __getattr__(self, attr: str) -> Item: ... + + model = construct_type( + type_=Model, + value={ + "a": {"prop": 1}, + "other": "foo", + }, + ) + assert isinstance(model, Model) + assert model.a.prop == 1 + assert isinstance(model.a, Item) + assert model.other == "foo" + + +# NOTE: Workaround for Pydantic Iterable behavior. +# Iterable fields are replaced with a ValidatorIterator and may be consumed +# during serialization, which can cause subsequent dumps to return empty data. +# See: https://github.com/pydantic/pydantic/issues/9541 +@pytest.mark.parametrize( + "data, expected_validated", + [ + ([1, 2, 3], [1, 2, 3]), + ((1, 2, 3), (1, 2, 3)), + (set([1, 2, 3]), set([1, 2, 3])), + (iter([1, 2, 3]), [1, 2, 3]), + ([], []), + ((x for x in [1, 2, 3]), [1, 2, 3]), + (map(lambda x: x, [1, 2, 3]), [1, 2, 3]), + (frozenset([1, 2, 3]), frozenset([1, 2, 3])), + (deque([1, 2, 3]), deque([1, 2, 3])), + ], + ids=["list", "tuple", "set", "iterator", "empty", "generator", "map", "frozenset", "deque"], +) +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2") +def test_iterable_construction(data: Iterable[int], expected_validated: Iterable[int]) -> None: + class TypeWithIterable(TypedDict): + items: EagerIterable[int] + + class Model(BaseModel): + data: TypeWithIterable + + m = Model.model_validate({"data": {"items": data}}) + assert m.data["items"] == expected_validated + + # Verify repeated dumps don't lose data (the original bug) + assert m.model_dump()["data"]["items"] == list(expected_validated) + assert m.model_dump()["data"]["items"] == list(expected_validated) + + +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2") +def test_iterable_construction_str_falls_back_to_list() -> None: + # str is iterable (over chars), but str(list_of_chars) produces the list's repr + # rather than reconstructing a string from items. We special-case str to fall + # back to list instead of attempting reconstruction. + class TypeWithIterable(TypedDict): + items: EagerIterable[str] + + class Model(BaseModel): + data: TypeWithIterable + + m = Model.model_validate({"data": {"items": "hello"}}) + + # falls back to list of chars rather than calling str(["h", "e", "l", "l", "o"]) + assert m.data["items"] == ["h", "e", "l", "l", "o"] + assert m.model_dump()["data"]["items"] == ["h", "e", "l", "l", "o"] diff --git a/tests/test_qs.py b/tests/test_qs.py new file mode 100644 index 00000000..e375584d --- /dev/null +++ b/tests/test_qs.py @@ -0,0 +1,78 @@ +from typing import Any, cast +from functools import partial +from urllib.parse import unquote + +import pytest + +from courier._qs import Querystring, stringify + + +def test_empty() -> None: + assert stringify({}) == "" + assert stringify({"a": {}}) == "" + assert stringify({"a": {"b": {"c": {}}}}) == "" + + +def test_basic() -> None: + assert stringify({"a": 1}) == "a=1" + assert stringify({"a": "b"}) == "a=b" + assert stringify({"a": True}) == "a=true" + assert stringify({"a": False}) == "a=false" + assert stringify({"a": 1.23456}) == "a=1.23456" + assert stringify({"a": None}) == "" + + +@pytest.mark.parametrize("method", ["class", "function"]) +def test_nested_dotted(method: str) -> None: + if method == "class": + serialise = Querystring(nested_format="dots").stringify + else: + serialise = partial(stringify, nested_format="dots") + + assert unquote(serialise({"a": {"b": "c"}})) == "a.b=c" + assert unquote(serialise({"a": {"b": "c", "d": "e", "f": "g"}})) == "a.b=c&a.d=e&a.f=g" + assert unquote(serialise({"a": {"b": {"c": {"d": "e"}}}})) == "a.b.c.d=e" + assert unquote(serialise({"a": {"b": True}})) == "a.b=true" + + +def test_nested_brackets() -> None: + assert unquote(stringify({"a": {"b": "c"}})) == "a[b]=c" + assert unquote(stringify({"a": {"b": "c", "d": "e", "f": "g"}})) == "a[b]=c&a[d]=e&a[f]=g" + assert unquote(stringify({"a": {"b": {"c": {"d": "e"}}}})) == "a[b][c][d]=e" + assert unquote(stringify({"a": {"b": True}})) == "a[b]=true" + + +@pytest.mark.parametrize("method", ["class", "function"]) +def test_array_comma(method: str) -> None: + if method == "class": + serialise = Querystring(array_format="comma").stringify + else: + serialise = partial(stringify, array_format="comma") + + assert unquote(serialise({"in": ["foo", "bar"]})) == "in=foo,bar" + assert unquote(serialise({"a": {"b": [True, False]}})) == "a[b]=true,false" + assert unquote(serialise({"a": {"b": [True, False, None, True]}})) == "a[b]=true,false,true" + + +def test_array_repeat() -> None: + assert unquote(stringify({"in": ["foo", "bar"]})) == "in=foo&in=bar" + assert unquote(stringify({"a": {"b": [True, False]}})) == "a[b]=true&a[b]=false" + assert unquote(stringify({"a": {"b": [True, False, None, True]}})) == "a[b]=true&a[b]=false&a[b]=true" + assert unquote(stringify({"in": ["foo", {"b": {"c": ["d", "e"]}}]})) == "in=foo&in[b][c]=d&in[b][c]=e" + + +@pytest.mark.parametrize("method", ["class", "function"]) +def test_array_brackets(method: str) -> None: + if method == "class": + serialise = Querystring(array_format="brackets").stringify + else: + serialise = partial(stringify, array_format="brackets") + + assert unquote(serialise({"in": ["foo", "bar"]})) == "in[]=foo&in[]=bar" + assert unquote(serialise({"a": {"b": [True, False]}})) == "a[b][]=true&a[b][]=false" + assert unquote(serialise({"a": {"b": [True, False, None, True]}})) == "a[b][]=true&a[b][]=false&a[b][]=true" + + +def test_unknown_array_format() -> None: + with pytest.raises(NotImplementedError, match="Unknown array_format value: foo, choose from comma, repeat"): + stringify({"a": ["foo", "bar"]}, array_format=cast(Any, "foo")) diff --git a/tests/test_required_args.py b/tests/test_required_args.py new file mode 100644 index 00000000..9b85e896 --- /dev/null +++ b/tests/test_required_args.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import pytest + +from courier._utils import required_args + + +def test_too_many_positional_params() -> None: + @required_args(["a"]) + def foo(a: str | None = None) -> str | None: + return a + + with pytest.raises(TypeError, match=r"foo\(\) takes 1 argument\(s\) but 2 were given"): + foo("a", "b") # type: ignore + + +def test_positional_param() -> None: + @required_args(["a"]) + def foo(a: str | None = None) -> str | None: + return a + + assert foo("a") == "a" + assert foo(None) is None + assert foo(a="b") == "b" + + with pytest.raises(TypeError, match="Missing required argument: 'a'"): + foo() + + +def test_keyword_only_param() -> None: + @required_args(["a"]) + def foo(*, a: str | None = None) -> str | None: + return a + + assert foo(a="a") == "a" + assert foo(a=None) is None + assert foo(a="b") == "b" + + with pytest.raises(TypeError, match="Missing required argument: 'a'"): + foo() + + +def test_multiple_params() -> None: + @required_args(["a", "b", "c"]) + def foo(a: str = "", *, b: str = "", c: str = "") -> str | None: + return f"{a} {b} {c}" + + assert foo(a="a", b="b", c="c") == "a b c" + + error_message = r"Missing required arguments.*" + + with pytest.raises(TypeError, match=error_message): + foo() + + with pytest.raises(TypeError, match=error_message): + foo(a="a") + + with pytest.raises(TypeError, match=error_message): + foo(b="b") + + with pytest.raises(TypeError, match=error_message): + foo(c="c") + + with pytest.raises(TypeError, match=r"Missing required argument: 'a'"): + foo(b="a", c="c") + + with pytest.raises(TypeError, match=r"Missing required argument: 'b'"): + foo("a", c="c") + + +def test_multiple_variants() -> None: + @required_args(["a"], ["b"]) + def foo(*, a: str | None = None, b: str | None = None) -> str | None: + return a if a is not None else b + + assert foo(a="foo") == "foo" + assert foo(b="bar") == "bar" + assert foo(a=None) is None + assert foo(b=None) is None + + # TODO: this error message could probably be improved + with pytest.raises( + TypeError, + match=r"Missing required arguments; Expected either \('a'\) or \('b'\) arguments to be given", + ): + foo() + + +def test_multiple_params_multiple_variants() -> None: + @required_args(["a", "b"], ["c"]) + def foo(*, a: str | None = None, b: str | None = None, c: str | None = None) -> str | None: + if a is not None: + return a + if b is not None: + return b + return c + + error_message = r"Missing required arguments; Expected either \('a' and 'b'\) or \('c'\) arguments to be given" + + with pytest.raises(TypeError, match=error_message): + foo(a="foo") + + with pytest.raises(TypeError, match=error_message): + foo(b="bar") + + with pytest.raises(TypeError, match=error_message): + foo() + + assert foo(a=None, b="bar") == "bar" + assert foo(c=None) is None + assert foo(c="foo") == "foo" diff --git a/tests/test_response.py b/tests/test_response.py new file mode 100644 index 00000000..0ba6c568 --- /dev/null +++ b/tests/test_response.py @@ -0,0 +1,277 @@ +import json +from typing import Any, List, Union, cast +from typing_extensions import Annotated + +import httpx +import pytest +import pydantic + +from courier import Courier, BaseModel, AsyncCourier +from courier._response import ( + APIResponse, + BaseAPIResponse, + AsyncAPIResponse, + BinaryAPIResponse, + AsyncBinaryAPIResponse, + extract_response_type, +) +from courier._streaming import Stream +from courier._base_client import FinalRequestOptions + + +class ConcreteBaseAPIResponse(APIResponse[bytes]): ... + + +class ConcreteAPIResponse(APIResponse[List[str]]): ... + + +class ConcreteAsyncAPIResponse(APIResponse[httpx.Response]): ... + + +def test_extract_response_type_direct_classes() -> None: + assert extract_response_type(BaseAPIResponse[str]) == str + assert extract_response_type(APIResponse[str]) == str + assert extract_response_type(AsyncAPIResponse[str]) == str + + +def test_extract_response_type_direct_class_missing_type_arg() -> None: + with pytest.raises( + RuntimeError, + match="Expected type to have a type argument at index 0 but it did not", + ): + extract_response_type(AsyncAPIResponse) + + +def test_extract_response_type_concrete_subclasses() -> None: + assert extract_response_type(ConcreteBaseAPIResponse) == bytes + assert extract_response_type(ConcreteAPIResponse) == List[str] + assert extract_response_type(ConcreteAsyncAPIResponse) == httpx.Response + + +def test_extract_response_type_binary_response() -> None: + assert extract_response_type(BinaryAPIResponse) == bytes + assert extract_response_type(AsyncBinaryAPIResponse) == bytes + + +class PydanticModel(pydantic.BaseModel): ... + + +def test_response_parse_mismatched_basemodel(client: Courier) -> None: + response = APIResponse( + raw=httpx.Response(200, content=b"foo"), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + with pytest.raises( + TypeError, + match="Pydantic models must subclass our base model type, e.g. `from courier import BaseModel`", + ): + response.parse(to=PydanticModel) + + +@pytest.mark.asyncio +async def test_async_response_parse_mismatched_basemodel(async_client: AsyncCourier) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=b"foo"), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + with pytest.raises( + TypeError, + match="Pydantic models must subclass our base model type, e.g. `from courier import BaseModel`", + ): + await response.parse(to=PydanticModel) + + +def test_response_parse_custom_stream(client: Courier) -> None: + response = APIResponse( + raw=httpx.Response(200, content=b"foo"), + client=client, + stream=True, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + stream = response.parse(to=Stream[int]) + assert stream._cast_to == int + + +@pytest.mark.asyncio +async def test_async_response_parse_custom_stream(async_client: AsyncCourier) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=b"foo"), + client=async_client, + stream=True, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + stream = await response.parse(to=Stream[int]) + assert stream._cast_to == int + + +class CustomModel(BaseModel): + foo: str + bar: int + + +def test_response_parse_custom_model(client: Courier) -> None: + response = APIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=CustomModel) + assert obj.foo == "hello!" + assert obj.bar == 2 + + +@pytest.mark.asyncio +async def test_async_response_parse_custom_model(async_client: AsyncCourier) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse(to=CustomModel) + assert obj.foo == "hello!" + assert obj.bar == 2 + + +def test_response_parse_annotated_type(client: Courier) -> None: + response = APIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse( + to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), + ) + assert obj.foo == "hello!" + assert obj.bar == 2 + + +async def test_async_response_parse_annotated_type(async_client: AsyncCourier) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse( + to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), + ) + assert obj.foo == "hello!" + assert obj.bar == 2 + + +@pytest.mark.parametrize( + "content, expected", + [ + ("false", False), + ("true", True), + ("False", False), + ("True", True), + ("TrUe", True), + ("FalSe", False), + ], +) +def test_response_parse_bool(client: Courier, content: str, expected: bool) -> None: + response = APIResponse( + raw=httpx.Response(200, content=content), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + result = response.parse(to=bool) + assert result is expected + + +@pytest.mark.parametrize( + "content, expected", + [ + ("false", False), + ("true", True), + ("False", False), + ("True", True), + ("TrUe", True), + ("FalSe", False), + ], +) +async def test_async_response_parse_bool(client: AsyncCourier, content: str, expected: bool) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=content), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + result = await response.parse(to=bool) + assert result is expected + + +class OtherModel(BaseModel): + a: str + + +@pytest.mark.parametrize("client", [False], indirect=True) # loose validation +def test_response_parse_expect_model_union_non_json_content(client: Courier) -> None: + response = APIResponse( + raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=cast(Any, Union[CustomModel, OtherModel])) + assert isinstance(obj, str) + assert obj == "foo" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_client", [False], indirect=True) # loose validation +async def test_async_response_parse_expect_model_union_non_json_content(async_client: AsyncCourier) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse(to=cast(Any, Union[CustomModel, OtherModel])) + assert isinstance(obj, str) + assert obj == "foo" diff --git a/tests/test_streaming.py b/tests/test_streaming.py new file mode 100644 index 00000000..69f0c9f2 --- /dev/null +++ b/tests/test_streaming.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +from typing import Iterator, AsyncIterator + +import httpx +import pytest + +from courier import Courier, AsyncCourier +from courier._streaming import Stream, AsyncStream, ServerSentEvent + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_basic(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: completion\n" + yield b'data: {"foo":true}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "completion" + assert sse.json() == {"foo": True} + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_data_missing_event(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b'data: {"foo":true}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"foo": True} + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_event_missing_data(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.data == "" + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_events(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"\n" + yield b"event: completion\n" + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.data == "" + + sse = await iter_next(iterator) + assert sse.event == "completion" + assert sse.data == "" + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_events_with_data(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b'data: {"foo":true}\n' + yield b"\n" + yield b"event: completion\n" + yield b'data: {"bar":false}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": True} + + sse = await iter_next(iterator) + assert sse.event == "completion" + assert sse.json() == {"bar": False} + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_data_lines_with_empty_line(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"data: {\n" + yield b'data: "foo":\n' + yield b"data: \n" + yield b"data:\n" + yield b"data: true}\n" + yield b"\n\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": True} + assert sse.data == '{\n"foo":\n\n\ntrue}' + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_data_json_escaped_double_new_line(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b'data: {"foo": "my long\\n\\ncontent"}' + yield b"\n\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": "my long\n\ncontent"} + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_data_lines(sync: bool, client: Courier, async_client: AsyncCourier) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"data: {\n" + yield b'data: "foo":\n' + yield b"data: true}\n" + yield b"\n\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": True} + + await assert_empty_iter(iterator) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_special_new_line_character( + sync: bool, + client: Courier, + async_client: AsyncCourier, +) -> None: + def body() -> Iterator[bytes]: + yield b'data: {"content":" culpa"}\n' + yield b"\n" + yield b'data: {"content":" \xe2\x80\xa8"}\n' + yield b"\n" + yield b'data: {"content":"foo"}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": " culpa"} + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": " 
"} + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": "foo"} + + await assert_empty_iter(iterator) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multi_byte_character_multiple_chunks( + sync: bool, + client: Courier, + async_client: AsyncCourier, +) -> None: + def body() -> Iterator[bytes]: + yield b'data: {"content":"' + # bytes taken from the string 'известни' and arbitrarily split + # so that some multi-byte characters span multiple chunks + yield b"\xd0" + yield b"\xb8\xd0\xb7\xd0" + yield b"\xb2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbd\xd0\xb8" + yield b'"}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": "известни"} + + +async def to_aiter(iter: Iterator[bytes]) -> AsyncIterator[bytes]: + for chunk in iter: + yield chunk + + +async def iter_next(iter: Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]) -> ServerSentEvent: + if isinstance(iter, AsyncIterator): + return await iter.__anext__() + + return next(iter) + + +async def assert_empty_iter(iter: Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]) -> None: + with pytest.raises((StopAsyncIteration, RuntimeError)): + await iter_next(iter) + + +def make_event_iterator( + content: Iterator[bytes], + *, + sync: bool, + client: Courier, + async_client: AsyncCourier, +) -> Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]: + if sync: + return Stream(cast_to=object, client=client, response=httpx.Response(200, content=content))._iter_events() + + return AsyncStream( + cast_to=object, client=async_client, response=httpx.Response(200, content=to_aiter(content)) + )._iter_events() diff --git a/tests/test_transform.py b/tests/test_transform.py new file mode 100644 index 00000000..588a9cd1 --- /dev/null +++ b/tests/test_transform.py @@ -0,0 +1,460 @@ +from __future__ import annotations + +import io +import pathlib +from typing import Any, Dict, List, Union, TypeVar, Iterable, Optional, cast +from datetime import date, datetime +from typing_extensions import Required, Annotated, TypedDict + +import pytest + +from courier._types import Base64FileInput, omit, not_given +from courier._utils import ( + PropertyInfo, + transform as _transform, + parse_datetime, + async_transform as _async_transform, +) +from courier._compat import PYDANTIC_V1 +from courier._models import BaseModel + +_T = TypeVar("_T") + +SAMPLE_FILE_PATH = pathlib.Path(__file__).parent.joinpath("sample_file.txt") + + +async def transform( + data: _T, + expected_type: object, + use_async: bool, +) -> _T: + if use_async: + return await _async_transform(data, expected_type=expected_type) + + return _transform(data, expected_type=expected_type) + + +parametrize = pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) + + +class Foo1(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +@parametrize +@pytest.mark.asyncio +async def test_top_level_alias(use_async: bool) -> None: + assert await transform({"foo_bar": "hello"}, expected_type=Foo1, use_async=use_async) == {"fooBar": "hello"} + + +class Foo2(TypedDict): + bar: Bar2 + + +class Bar2(TypedDict): + this_thing: Annotated[int, PropertyInfo(alias="this__thing")] + baz: Annotated[Baz2, PropertyInfo(alias="Baz")] + + +class Baz2(TypedDict): + my_baz: Annotated[str, PropertyInfo(alias="myBaz")] + + +@parametrize +@pytest.mark.asyncio +async def test_recursive_typeddict(use_async: bool) -> None: + assert await transform({"bar": {"this_thing": 1}}, Foo2, use_async) == {"bar": {"this__thing": 1}} + assert await transform({"bar": {"baz": {"my_baz": "foo"}}}, Foo2, use_async) == {"bar": {"Baz": {"myBaz": "foo"}}} + + +class Foo3(TypedDict): + things: List[Bar3] + + +class Bar3(TypedDict): + my_field: Annotated[str, PropertyInfo(alias="myField")] + + +@parametrize +@pytest.mark.asyncio +async def test_list_of_typeddict(use_async: bool) -> None: + result = await transform({"things": [{"my_field": "foo"}, {"my_field": "foo2"}]}, Foo3, use_async) + assert result == {"things": [{"myField": "foo"}, {"myField": "foo2"}]} + + +class Foo4(TypedDict): + foo: Union[Bar4, Baz4] + + +class Bar4(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +class Baz4(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + +@parametrize +@pytest.mark.asyncio +async def test_union_of_typeddict(use_async: bool) -> None: + assert await transform({"foo": {"foo_bar": "bar"}}, Foo4, use_async) == {"foo": {"fooBar": "bar"}} + assert await transform({"foo": {"foo_baz": "baz"}}, Foo4, use_async) == {"foo": {"fooBaz": "baz"}} + assert await transform({"foo": {"foo_baz": "baz", "foo_bar": "bar"}}, Foo4, use_async) == { + "foo": {"fooBaz": "baz", "fooBar": "bar"} + } + + +class Foo5(TypedDict): + foo: Annotated[Union[Bar4, List[Baz4]], PropertyInfo(alias="FOO")] + + +class Bar5(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +class Baz5(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + +@parametrize +@pytest.mark.asyncio +async def test_union_of_list(use_async: bool) -> None: + assert await transform({"foo": {"foo_bar": "bar"}}, Foo5, use_async) == {"FOO": {"fooBar": "bar"}} + assert await transform( + { + "foo": [ + {"foo_baz": "baz"}, + {"foo_baz": "baz"}, + ] + }, + Foo5, + use_async, + ) == {"FOO": [{"fooBaz": "baz"}, {"fooBaz": "baz"}]} + + +class Foo6(TypedDict): + bar: Annotated[str, PropertyInfo(alias="Bar")] + + +@parametrize +@pytest.mark.asyncio +async def test_includes_unknown_keys(use_async: bool) -> None: + assert await transform({"bar": "bar", "baz_": {"FOO": 1}}, Foo6, use_async) == { + "Bar": "bar", + "baz_": {"FOO": 1}, + } + + +class Foo7(TypedDict): + bar: Annotated[List[Bar7], PropertyInfo(alias="bAr")] + foo: Bar7 + + +class Bar7(TypedDict): + foo: str + + +@parametrize +@pytest.mark.asyncio +async def test_ignores_invalid_input(use_async: bool) -> None: + assert await transform({"bar": ""}, Foo7, use_async) == {"bAr": ""} + assert await transform({"foo": ""}, Foo7, use_async) == {"foo": ""} + + +class DatetimeDict(TypedDict, total=False): + foo: Annotated[datetime, PropertyInfo(format="iso8601")] + + bar: Annotated[Optional[datetime], PropertyInfo(format="iso8601")] + + required: Required[Annotated[Optional[datetime], PropertyInfo(format="iso8601")]] + + list_: Required[Annotated[Optional[List[datetime]], PropertyInfo(format="iso8601")]] + + union: Annotated[Union[int, datetime], PropertyInfo(format="iso8601")] + + +class DateDict(TypedDict, total=False): + foo: Annotated[date, PropertyInfo(format="iso8601")] + + +class DatetimeModel(BaseModel): + foo: datetime + + +class DateModel(BaseModel): + foo: Optional[date] + + +@parametrize +@pytest.mark.asyncio +async def test_iso8601_format(use_async: bool) -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + tz = "+00:00" if PYDANTIC_V1 else "Z" + assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692" + tz} # type: ignore[comparison-overlap] + + dt = dt.replace(tzinfo=None) + assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] + assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] + + assert await transform({"foo": None}, DateDict, use_async) == {"foo": None} # type: ignore[comparison-overlap] + assert await transform(DateModel(foo=None), Any, use_async) == {"foo": None} # type: ignore + assert await transform({"foo": date.fromisoformat("2023-02-23")}, DateDict, use_async) == {"foo": "2023-02-23"} # type: ignore[comparison-overlap] + assert await transform(DateModel(foo=date.fromisoformat("2023-02-23")), DateDict, use_async) == { + "foo": "2023-02-23" + } # type: ignore[comparison-overlap] + + +@parametrize +@pytest.mark.asyncio +async def test_optional_iso8601_format(use_async: bool) -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert await transform({"bar": dt}, DatetimeDict, use_async) == {"bar": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + + assert await transform({"bar": None}, DatetimeDict, use_async) == {"bar": None} + + +@parametrize +@pytest.mark.asyncio +async def test_required_iso8601_format(use_async: bool) -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert await transform({"required": dt}, DatetimeDict, use_async) == { + "required": "2023-02-23T14:16:36.337692+00:00" + } # type: ignore[comparison-overlap] + + assert await transform({"required": None}, DatetimeDict, use_async) == {"required": None} + + +@parametrize +@pytest.mark.asyncio +async def test_union_datetime(use_async: bool) -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert await transform({"union": dt}, DatetimeDict, use_async) == { # type: ignore[comparison-overlap] + "union": "2023-02-23T14:16:36.337692+00:00" + } + + assert await transform({"union": "foo"}, DatetimeDict, use_async) == {"union": "foo"} + + +@parametrize +@pytest.mark.asyncio +async def test_nested_list_iso6801_format(use_async: bool) -> None: + dt1 = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + dt2 = parse_datetime("2022-01-15T06:34:23Z") + assert await transform({"list_": [dt1, dt2]}, DatetimeDict, use_async) == { # type: ignore[comparison-overlap] + "list_": ["2023-02-23T14:16:36.337692+00:00", "2022-01-15T06:34:23+00:00"] + } + + +@parametrize +@pytest.mark.asyncio +async def test_datetime_custom_format(use_async: bool) -> None: + dt = parse_datetime("2022-01-15T06:34:23Z") + + result = await transform(dt, Annotated[datetime, PropertyInfo(format="custom", format_template="%H")], use_async) + assert result == "06" # type: ignore[comparison-overlap] + + +class DateDictWithRequiredAlias(TypedDict, total=False): + required_prop: Required[Annotated[date, PropertyInfo(format="iso8601", alias="prop")]] + + +@parametrize +@pytest.mark.asyncio +async def test_datetime_with_alias(use_async: bool) -> None: + assert await transform({"required_prop": None}, DateDictWithRequiredAlias, use_async) == {"prop": None} # type: ignore[comparison-overlap] + assert await transform( + {"required_prop": date.fromisoformat("2023-02-23")}, DateDictWithRequiredAlias, use_async + ) == {"prop": "2023-02-23"} # type: ignore[comparison-overlap] + + +class MyModel(BaseModel): + foo: str + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_model_to_dictionary(use_async: bool) -> None: + assert cast(Any, await transform(MyModel(foo="hi!"), Any, use_async)) == {"foo": "hi!"} + assert cast(Any, await transform(MyModel.construct(foo="hi!"), Any, use_async)) == {"foo": "hi!"} + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_empty_model(use_async: bool) -> None: + assert cast(Any, await transform(MyModel.construct(), Any, use_async)) == {} + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_unknown_field(use_async: bool) -> None: + assert cast(Any, await transform(MyModel.construct(my_untyped_field=True), Any, use_async)) == { + "my_untyped_field": True + } + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_mismatched_types(use_async: bool) -> None: + model = MyModel.construct(foo=True) + if PYDANTIC_V1: + params = await transform(model, Any, use_async) + else: + with pytest.warns(UserWarning): + params = await transform(model, Any, use_async) + assert cast(Any, params) == {"foo": True} + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_mismatched_object_type(use_async: bool) -> None: + model = MyModel.construct(foo=MyModel.construct(hello="world")) + if PYDANTIC_V1: + params = await transform(model, Any, use_async) + else: + with pytest.warns(UserWarning): + params = await transform(model, Any, use_async) + assert cast(Any, params) == {"foo": {"hello": "world"}} + + +class ModelNestedObjects(BaseModel): + nested: MyModel + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_nested_objects(use_async: bool) -> None: + model = ModelNestedObjects.construct(nested={"foo": "stainless"}) + assert isinstance(model.nested, MyModel) + assert cast(Any, await transform(model, Any, use_async)) == {"nested": {"foo": "stainless"}} + + +class ModelWithDefaultField(BaseModel): + foo: str + with_none_default: Union[str, None] = None + with_str_default: str = "foo" + + +@parametrize +@pytest.mark.asyncio +async def test_pydantic_default_field(use_async: bool) -> None: + # should be excluded when defaults are used + model = ModelWithDefaultField.construct() + assert model.with_none_default is None + assert model.with_str_default == "foo" + assert cast(Any, await transform(model, Any, use_async)) == {} + + # should be included when the default value is explicitly given + model = ModelWithDefaultField.construct(with_none_default=None, with_str_default="foo") + assert model.with_none_default is None + assert model.with_str_default == "foo" + assert cast(Any, await transform(model, Any, use_async)) == {"with_none_default": None, "with_str_default": "foo"} + + # should be included when a non-default value is explicitly given + model = ModelWithDefaultField.construct(with_none_default="bar", with_str_default="baz") + assert model.with_none_default == "bar" + assert model.with_str_default == "baz" + assert cast(Any, await transform(model, Any, use_async)) == {"with_none_default": "bar", "with_str_default": "baz"} + + +class TypedDictIterableUnion(TypedDict): + foo: Annotated[Union[Bar8, Iterable[Baz8]], PropertyInfo(alias="FOO")] + + +class Bar8(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +class Baz8(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + +@parametrize +@pytest.mark.asyncio +async def test_iterable_of_dictionaries(use_async: bool) -> None: + assert await transform({"foo": [{"foo_baz": "bar"}]}, TypedDictIterableUnion, use_async) == { + "FOO": [{"fooBaz": "bar"}] + } + assert cast(Any, await transform({"foo": ({"foo_baz": "bar"},)}, TypedDictIterableUnion, use_async)) == { + "FOO": [{"fooBaz": "bar"}] + } + + def my_iter() -> Iterable[Baz8]: + yield {"foo_baz": "hello"} + yield {"foo_baz": "world"} + + assert await transform({"foo": my_iter()}, TypedDictIterableUnion, use_async) == { + "FOO": [{"fooBaz": "hello"}, {"fooBaz": "world"}] + } + + +@parametrize +@pytest.mark.asyncio +async def test_dictionary_items(use_async: bool) -> None: + class DictItems(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + assert await transform({"foo": {"foo_baz": "bar"}}, Dict[str, DictItems], use_async) == {"foo": {"fooBaz": "bar"}} + + +class TypedDictIterableUnionStr(TypedDict): + foo: Annotated[Union[str, Iterable[Baz8]], PropertyInfo(alias="FOO")] + + +@parametrize +@pytest.mark.asyncio +async def test_iterable_union_str(use_async: bool) -> None: + assert await transform({"foo": "bar"}, TypedDictIterableUnionStr, use_async) == {"FOO": "bar"} + assert cast(Any, await transform(iter([{"foo_baz": "bar"}]), Union[str, Iterable[Baz8]], use_async)) == [ + {"fooBaz": "bar"} + ] + + +class TypedDictBase64Input(TypedDict): + foo: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + + +@parametrize +@pytest.mark.asyncio +async def test_base64_file_input(use_async: bool) -> None: + # strings are left as-is + assert await transform({"foo": "bar"}, TypedDictBase64Input, use_async) == {"foo": "bar"} + + # pathlib.Path is automatically converted to base64 + assert await transform({"foo": SAMPLE_FILE_PATH}, TypedDictBase64Input, use_async) == { + "foo": "SGVsbG8sIHdvcmxkIQo=" + } # type: ignore[comparison-overlap] + + # io instances are automatically converted to base64 + assert await transform({"foo": io.StringIO("Hello, world!")}, TypedDictBase64Input, use_async) == { + "foo": "SGVsbG8sIHdvcmxkIQ==" + } # type: ignore[comparison-overlap] + assert await transform({"foo": io.BytesIO(b"Hello, world!")}, TypedDictBase64Input, use_async) == { + "foo": "SGVsbG8sIHdvcmxkIQ==" + } # type: ignore[comparison-overlap] + + +@parametrize +@pytest.mark.asyncio +async def test_transform_skipping(use_async: bool) -> None: + # lists of ints are left as-is + data = [1, 2, 3] + assert await transform(data, List[int], use_async) is data + + # iterables of ints are converted to a list + data = iter([1, 2, 3]) + assert await transform(data, Iterable[int], use_async) == [1, 2, 3] + + +@parametrize +@pytest.mark.asyncio +async def test_strips_notgiven(use_async: bool) -> None: + assert await transform({"foo_bar": "bar"}, Foo1, use_async) == {"fooBar": "bar"} + assert await transform({"foo_bar": not_given}, Foo1, use_async) == {} + + +@parametrize +@pytest.mark.asyncio +async def test_strips_omit(use_async: bool) -> None: + assert await transform({"foo_bar": "bar"}, Foo1, use_async) == {"fooBar": "bar"} + assert await transform({"foo_bar": omit}, Foo1, use_async) == {} diff --git a/tests/test_utils/test_datetime_parse.py b/tests/test_utils/test_datetime_parse.py new file mode 100644 index 00000000..97673f75 --- /dev/null +++ b/tests/test_utils/test_datetime_parse.py @@ -0,0 +1,110 @@ +""" +Copied from https://github.com/pydantic/pydantic/blob/v1.10.22/tests/test_datetime_parse.py +with modifications so it works without pydantic v1 imports. +""" + +from typing import Type, Union +from datetime import date, datetime, timezone, timedelta + +import pytest + +from courier._utils import parse_date, parse_datetime + + +def create_tz(minutes: int) -> timezone: + return timezone(timedelta(minutes=minutes)) + + +@pytest.mark.parametrize( + "value,result", + [ + # Valid inputs + ("1494012444.883309", date(2017, 5, 5)), + (b"1494012444.883309", date(2017, 5, 5)), + (1_494_012_444.883_309, date(2017, 5, 5)), + ("1494012444", date(2017, 5, 5)), + (1_494_012_444, date(2017, 5, 5)), + (0, date(1970, 1, 1)), + ("2012-04-23", date(2012, 4, 23)), + (b"2012-04-23", date(2012, 4, 23)), + ("2012-4-9", date(2012, 4, 9)), + (date(2012, 4, 9), date(2012, 4, 9)), + (datetime(2012, 4, 9, 12, 15), date(2012, 4, 9)), + # Invalid inputs + ("x20120423", ValueError), + ("2012-04-56", ValueError), + (19_999_999_999, date(2603, 10, 11)), # just before watershed + (20_000_000_001, date(1970, 8, 20)), # just after watershed + (1_549_316_052, date(2019, 2, 4)), # nowish in s + (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms + (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs + (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns + ("infinity", date(9999, 12, 31)), + ("inf", date(9999, 12, 31)), + (float("inf"), date(9999, 12, 31)), + ("infinity ", date(9999, 12, 31)), + (int("1" + "0" * 100), date(9999, 12, 31)), + (1e1000, date(9999, 12, 31)), + ("-infinity", date(1, 1, 1)), + ("-inf", date(1, 1, 1)), + ("nan", ValueError), + ], +) +def test_date_parsing(value: Union[str, bytes, int, float], result: Union[date, Type[Exception]]) -> None: + if type(result) == type and issubclass(result, Exception): # pyright: ignore[reportUnnecessaryIsInstance] + with pytest.raises(result): + parse_date(value) + else: + assert parse_date(value) == result + + +@pytest.mark.parametrize( + "value,result", + [ + # Valid inputs + # values in seconds + ("1494012444.883309", datetime(2017, 5, 5, 19, 27, 24, 883_309, tzinfo=timezone.utc)), + (1_494_012_444.883_309, datetime(2017, 5, 5, 19, 27, 24, 883_309, tzinfo=timezone.utc)), + ("1494012444", datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + (b"1494012444", datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + (1_494_012_444, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + # values in ms + ("1494012444000.883309", datetime(2017, 5, 5, 19, 27, 24, 883, tzinfo=timezone.utc)), + ("-1494012444000.883309", datetime(1922, 8, 29, 4, 32, 35, 999117, tzinfo=timezone.utc)), + (1_494_012_444_000, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)), + ("2012-04-23T09:15:00", datetime(2012, 4, 23, 9, 15)), + ("2012-4-9 4:8:16", datetime(2012, 4, 9, 4, 8, 16)), + ("2012-04-23T09:15:00Z", datetime(2012, 4, 23, 9, 15, 0, 0, timezone.utc)), + ("2012-4-9 4:8:16-0320", datetime(2012, 4, 9, 4, 8, 16, 0, create_tz(-200))), + ("2012-04-23T10:20:30.400+02:30", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(150))), + ("2012-04-23T10:20:30.400+02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(120))), + ("2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))), + (b"2012-04-23T10:20:30.400-02", datetime(2012, 4, 23, 10, 20, 30, 400_000, create_tz(-120))), + (datetime(2017, 5, 5), datetime(2017, 5, 5)), + (0, datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + # Invalid inputs + ("x20120423091500", ValueError), + ("2012-04-56T09:15:90", ValueError), + ("2012-04-23T11:05:00-25:00", ValueError), + (19_999_999_999, datetime(2603, 10, 11, 11, 33, 19, tzinfo=timezone.utc)), # just before watershed + (20_000_000_001, datetime(1970, 8, 20, 11, 33, 20, 1000, tzinfo=timezone.utc)), # just after watershed + (1_549_316_052, datetime(2019, 2, 4, 21, 34, 12, 0, tzinfo=timezone.utc)), # nowish in s + (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms + (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs + (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in ns + ("infinity", datetime(9999, 12, 31, 23, 59, 59, 999999)), + ("inf", datetime(9999, 12, 31, 23, 59, 59, 999999)), + ("inf ", datetime(9999, 12, 31, 23, 59, 59, 999999)), + (1e50, datetime(9999, 12, 31, 23, 59, 59, 999999)), + (float("inf"), datetime(9999, 12, 31, 23, 59, 59, 999999)), + ("-infinity", datetime(1, 1, 1, 0, 0)), + ("-inf", datetime(1, 1, 1, 0, 0)), + ("nan", ValueError), + ], +) +def test_datetime_parsing(value: Union[str, bytes, int, float], result: Union[datetime, Type[Exception]]) -> None: + if type(result) == type and issubclass(result, Exception): # pyright: ignore[reportUnnecessaryIsInstance] + with pytest.raises(result): + parse_datetime(value) + else: + assert parse_datetime(value) == result diff --git a/tests/test_utils/test_json.py b/tests/test_utils/test_json.py new file mode 100644 index 00000000..3f40e78e --- /dev/null +++ b/tests/test_utils/test_json.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import datetime +from typing import Union + +import pydantic + +from courier import _compat +from courier._utils._json import openapi_dumps + + +class TestOpenapiDumps: + def test_basic(self) -> None: + data = {"key": "value", "number": 42} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"key":"value","number":42}' + + def test_datetime_serialization(self) -> None: + dt = datetime.datetime(2023, 1, 1, 12, 0, 0) + data = {"datetime": dt} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"datetime":"2023-01-01T12:00:00"}' + + def test_pydantic_model_serialization(self) -> None: + class User(pydantic.BaseModel): + first_name: str + last_name: str + age: int + + model_instance = User(first_name="John", last_name="Kramer", age=83) + data = {"model": model_instance} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"first_name":"John","last_name":"Kramer","age":83}}' + + def test_pydantic_model_with_default_values(self) -> None: + class User(pydantic.BaseModel): + name: str + role: str = "user" + active: bool = True + score: int = 0 + + model_instance = User(name="Alice") + data = {"model": model_instance} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"name":"Alice"}}' + + def test_pydantic_model_with_default_values_overridden(self) -> None: + class User(pydantic.BaseModel): + name: str + role: str = "user" + active: bool = True + + model_instance = User(name="Bob", role="admin", active=False) + data = {"model": model_instance} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"name":"Bob","role":"admin","active":false}}' + + def test_pydantic_model_with_alias(self) -> None: + class User(pydantic.BaseModel): + first_name: str = pydantic.Field(alias="firstName") + last_name: str = pydantic.Field(alias="lastName") + + model_instance = User(firstName="John", lastName="Doe") + data = {"model": model_instance} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"firstName":"John","lastName":"Doe"}}' + + def test_pydantic_model_with_alias_and_default(self) -> None: + class User(pydantic.BaseModel): + user_name: str = pydantic.Field(alias="userName") + user_role: str = pydantic.Field(default="member", alias="userRole") + is_active: bool = pydantic.Field(default=True, alias="isActive") + + model_instance = User(userName="charlie") + data = {"model": model_instance} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"userName":"charlie"}}' + + model_with_overrides = User(userName="diana", userRole="admin", isActive=False) + data = {"model": model_with_overrides} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"userName":"diana","userRole":"admin","isActive":false}}' + + def test_pydantic_model_with_nested_models_and_defaults(self) -> None: + class Address(pydantic.BaseModel): + street: str + city: str = "Unknown" + + class User(pydantic.BaseModel): + name: str + address: Address + verified: bool = False + + if _compat.PYDANTIC_V1: + # to handle forward references in Pydantic v1 + User.update_forward_refs(**locals()) # type: ignore[reportDeprecated] + + address = Address(street="123 Main St") + user = User(name="Diana", address=address) + data = {"user": user} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"user":{"name":"Diana","address":{"street":"123 Main St"}}}' + + address_with_city = Address(street="456 Oak Ave", city="Boston") + user_verified = User(name="Eve", address=address_with_city, verified=True) + data = {"user": user_verified} + json_bytes = openapi_dumps(data) + assert ( + json_bytes == b'{"user":{"name":"Eve","address":{"street":"456 Oak Ave","city":"Boston"},"verified":true}}' + ) + + def test_pydantic_model_with_optional_fields(self) -> None: + class User(pydantic.BaseModel): + name: str + email: Union[str, None] + phone: Union[str, None] + + model_with_none = User(name="Eve", email=None, phone=None) + data = {"model": model_with_none} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"name":"Eve","email":null,"phone":null}}' + + model_with_values = User(name="Frank", email="frank@example.com", phone=None) + data = {"model": model_with_values} + json_bytes = openapi_dumps(data) + assert json_bytes == b'{"model":{"name":"Frank","email":"frank@example.com","phone":null}}' diff --git a/tests/test_utils/test_path.py b/tests/test_utils/test_path.py new file mode 100644 index 00000000..7a72c7b4 --- /dev/null +++ b/tests/test_utils/test_path.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from typing import Any + +import pytest + +from courier._utils._path import path_template + + +@pytest.mark.parametrize( + "template, kwargs, expected", + [ + ("/v1/{id}", dict(id="abc"), "/v1/abc"), + ("/v1/{a}/{b}", dict(a="x", b="y"), "/v1/x/y"), + ("/v1/{a}{b}/path/{c}?val={d}#{e}", dict(a="x", b="y", c="z", d="u", e="v"), "/v1/xy/path/z?val=u#v"), + ("/{w}/{w}", dict(w="echo"), "/echo/echo"), + ("/v1/static", {}, "/v1/static"), + ("", {}, ""), + ("/v1/?q={n}&count=10", dict(n=42), "/v1/?q=42&count=10"), + ("/v1/{v}", dict(v=None), "/v1/null"), + ("/v1/{v}", dict(v=True), "/v1/true"), + ("/v1/{v}", dict(v=False), "/v1/false"), + ("/v1/{v}", dict(v=".hidden"), "/v1/.hidden"), # dot prefix ok + ("/v1/{v}", dict(v="file.txt"), "/v1/file.txt"), # dot in middle ok + ("/v1/{v}", dict(v="..."), "/v1/..."), # triple dot ok + ("/v1/{a}{b}", dict(a=".", b="txt"), "/v1/.txt"), # dot var combining with adjacent to be ok + ("/items?q={v}#{f}", dict(v=".", f=".."), "/items?q=.#.."), # dots in query/fragment are fine + ( + "/v1/{a}?query={b}", + dict(a="../../other/endpoint", b="a&bad=true"), + "/v1/..%2F..%2Fother%2Fendpoint?query=a%26bad%3Dtrue", + ), + ("/v1/{val}", dict(val="a/b/c"), "/v1/a%2Fb%2Fc"), + ("/v1/{val}", dict(val="a/b/c?query=value"), "/v1/a%2Fb%2Fc%3Fquery=value"), + ("/v1/{val}", dict(val="a/b/c?query=value&bad=true"), "/v1/a%2Fb%2Fc%3Fquery=value&bad=true"), + ("/v1/{val}", dict(val="%20"), "/v1/%2520"), # escapes escape sequences in input + # Query: slash and ? are safe, # is not + ("/items?q={v}", dict(v="a/b"), "/items?q=a/b"), + ("/items?q={v}", dict(v="a?b"), "/items?q=a?b"), + ("/items?q={v}", dict(v="a#b"), "/items?q=a%23b"), + ("/items?q={v}", dict(v="a b"), "/items?q=a%20b"), + # Fragment: slash and ? are safe + ("/docs#{v}", dict(v="a/b"), "/docs#a/b"), + ("/docs#{v}", dict(v="a?b"), "/docs#a?b"), + # Path: slash, ? and # are all encoded + ("/v1/{v}", dict(v="a/b"), "/v1/a%2Fb"), + ("/v1/{v}", dict(v="a?b"), "/v1/a%3Fb"), + ("/v1/{v}", dict(v="a#b"), "/v1/a%23b"), + # same var encoded differently by component + ( + "/v1/{v}?q={v}#{v}", + dict(v="a/b?c#d"), + "/v1/a%2Fb%3Fc%23d?q=a/b?c%23d#a/b?c%23d", + ), + ("/v1/{val}", dict(val="x?admin=true"), "/v1/x%3Fadmin=true"), # query injection + ("/v1/{val}", dict(val="x#admin"), "/v1/x%23admin"), # fragment injection + ], +) +def test_interpolation(template: str, kwargs: dict[str, Any], expected: str) -> None: + assert path_template(template, **kwargs) == expected + + +def test_missing_kwarg_raises_key_error() -> None: + with pytest.raises(KeyError, match="org_id"): + path_template("/v1/{org_id}") + + +@pytest.mark.parametrize( + "template, kwargs", + [ + ("{a}/path", dict(a=".")), + ("{a}/path", dict(a="..")), + ("/v1/{a}", dict(a=".")), + ("/v1/{a}", dict(a="..")), + ("/v1/{a}/path", dict(a=".")), + ("/v1/{a}/path", dict(a="..")), + ("/v1/{a}{b}", dict(a=".", b=".")), # adjacent vars → ".." + ("/v1/{a}.", dict(a=".")), # var + static → ".." + ("/v1/{a}{b}", dict(a="", b=".")), # empty + dot → "." + ("/v1/%2e/{x}", dict(x="ok")), # encoded dot in static text + ("/v1/%2e./{x}", dict(x="ok")), # mixed encoded ".." in static + ("/v1/.%2E/{x}", dict(x="ok")), # mixed encoded ".." in static + ("/v1/{v}?q=1", dict(v="..")), + ("/v1/{v}#frag", dict(v="..")), + ], +) +def test_dot_segment_rejected(template: str, kwargs: dict[str, Any]) -> None: + with pytest.raises(ValueError, match="dot-segment"): + path_template(template, **kwargs) diff --git a/tests/test_utils/test_proxy.py b/tests/test_utils/test_proxy.py new file mode 100644 index 00000000..0b6e125e --- /dev/null +++ b/tests/test_utils/test_proxy.py @@ -0,0 +1,34 @@ +import operator +from typing import Any +from typing_extensions import override + +from courier._utils import LazyProxy + + +class RecursiveLazyProxy(LazyProxy[Any]): + @override + def __load__(self) -> Any: + return self + + def __call__(self, *_args: Any, **_kwds: Any) -> Any: + raise RuntimeError("This should never be called!") + + +def test_recursive_proxy() -> None: + proxy = RecursiveLazyProxy() + assert repr(proxy) == "RecursiveLazyProxy" + assert str(proxy) == "RecursiveLazyProxy" + assert dir(proxy) == [] + assert type(proxy).__name__ == "RecursiveLazyProxy" + assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy" + + +def test_isinstance_does_not_error() -> None: + class AlwaysErrorProxy(LazyProxy[Any]): + @override + def __load__(self) -> Any: + raise RuntimeError("Mocking missing dependency") + + proxy = AlwaysErrorProxy() + assert not isinstance(proxy, dict) + assert isinstance(proxy, LazyProxy) diff --git a/tests/test_utils/test_typing.py b/tests/test_utils/test_typing.py new file mode 100644 index 00000000..ca2a2072 --- /dev/null +++ b/tests/test_utils/test_typing.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import Generic, TypeVar, cast + +from courier._utils import extract_type_var_from_base + +_T = TypeVar("_T") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") + + +class BaseGeneric(Generic[_T]): ... + + +class SubclassGeneric(BaseGeneric[_T]): ... + + +class BaseGenericMultipleTypeArgs(Generic[_T, _T2, _T3]): ... + + +class SubclassGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T, _T2, _T3]): ... + + +class SubclassDifferentOrderGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T2, _T, _T3]): ... + + +def test_extract_type_var() -> None: + assert ( + extract_type_var_from_base( + BaseGeneric[int], + index=0, + generic_bases=cast("tuple[type, ...]", (BaseGeneric,)), + ) + == int + ) + + +def test_extract_type_var_generic_subclass() -> None: + assert ( + extract_type_var_from_base( + SubclassGeneric[int], + index=0, + generic_bases=cast("tuple[type, ...]", (BaseGeneric,)), + ) + == int + ) + + +def test_extract_type_var_multiple() -> None: + typ = BaseGenericMultipleTypeArgs[int, str, None] + + generic_bases = cast("tuple[type, ...]", (BaseGenericMultipleTypeArgs,)) + assert extract_type_var_from_base(typ, index=0, generic_bases=generic_bases) == int + assert extract_type_var_from_base(typ, index=1, generic_bases=generic_bases) == str + assert extract_type_var_from_base(typ, index=2, generic_bases=generic_bases) == type(None) + + +def test_extract_type_var_generic_subclass_multiple() -> None: + typ = SubclassGenericMultipleTypeArgs[int, str, None] + + generic_bases = cast("tuple[type, ...]", (BaseGenericMultipleTypeArgs,)) + assert extract_type_var_from_base(typ, index=0, generic_bases=generic_bases) == int + assert extract_type_var_from_base(typ, index=1, generic_bases=generic_bases) == str + assert extract_type_var_from_base(typ, index=2, generic_bases=generic_bases) == type(None) + + +def test_extract_type_var_generic_subclass_different_ordering_multiple() -> None: + typ = SubclassDifferentOrderGenericMultipleTypeArgs[int, str, None] + + generic_bases = cast("tuple[type, ...]", (BaseGenericMultipleTypeArgs,)) + assert extract_type_var_from_base(typ, index=0, generic_bases=generic_bases) == int + assert extract_type_var_from_base(typ, index=1, generic_bases=generic_bases) == str + assert extract_type_var_from_base(typ, index=2, generic_bases=generic_bases) == type(None) diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 00000000..6a648f8f --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import os +import inspect +import traceback +import contextlib +from typing import Any, TypeVar, Iterator, Sequence, cast +from datetime import date, datetime +from typing_extensions import Literal, get_args, get_origin, assert_type + +from courier._types import Omit, NoneType +from courier._utils import ( + is_dict, + is_list, + is_list_type, + is_union_type, + extract_type_arg, + is_sequence_type, + is_annotated_type, + is_type_alias_type, +) +from courier._compat import PYDANTIC_V1, field_outer_type, get_model_fields +from courier._models import BaseModel + +BaseModelT = TypeVar("BaseModelT", bound=BaseModel) + + +def assert_matches_model(model: type[BaseModelT], value: BaseModelT, *, path: list[str]) -> bool: + for name, field in get_model_fields(model).items(): + field_value = getattr(value, name) + if PYDANTIC_V1: + # in v1 nullability was structured differently + # https://docs.pydantic.dev/2.0/migration/#required-optional-and-nullable-fields + allow_none = getattr(field, "allow_none", False) + else: + allow_none = False + + assert_matches_type( + field_outer_type(field), + field_value, + path=[*path, name], + allow_none=allow_none, + ) + + return True + + +# Note: the `path` argument is only used to improve error messages when `--showlocals` is used +def assert_matches_type( + type_: Any, + value: object, + *, + path: list[str], + allow_none: bool = False, +) -> None: + if is_type_alias_type(type_): + type_ = type_.__value__ + + # unwrap `Annotated[T, ...]` -> `T` + if is_annotated_type(type_): + type_ = extract_type_arg(type_, 0) + + if allow_none and value is None: + return + + if type_ is None or type_ is NoneType: + assert value is None + return + + origin = get_origin(type_) or type_ + + if is_list_type(type_): + return _assert_list_type(type_, value) + + if is_sequence_type(type_): + assert isinstance(value, Sequence) + inner_type = get_args(type_)[0] + for entry in value: # type: ignore + assert_type(inner_type, entry) # type: ignore + return + + if origin == str: + assert isinstance(value, str) + elif origin == int: + assert isinstance(value, int) + elif origin == bool: + assert isinstance(value, bool) + elif origin == float: + assert isinstance(value, float) + elif origin == bytes: + assert isinstance(value, bytes) + elif origin == datetime: + assert isinstance(value, datetime) + elif origin == date: + assert isinstance(value, date) + elif origin == object: + # nothing to do here, the expected type is unknown + pass + elif origin == Literal: + assert value in get_args(type_) + elif origin == dict: + assert is_dict(value) + + args = get_args(type_) + key_type = args[0] + items_type = args[1] + + for key, item in value.items(): + assert_matches_type(key_type, key, path=[*path, ""]) + assert_matches_type(items_type, item, path=[*path, ""]) + elif is_union_type(type_): + variants = get_args(type_) + + try: + none_index = variants.index(type(None)) + except ValueError: + pass + else: + # special case Optional[T] for better error messages + if len(variants) == 2: + if value is None: + # valid + return + + return assert_matches_type(type_=variants[not none_index], value=value, path=path) + + for i, variant in enumerate(variants): + try: + assert_matches_type(variant, value, path=[*path, f"variant {i}"]) + return + except AssertionError: + traceback.print_exc() + continue + + raise AssertionError("Did not match any variants") + elif issubclass(origin, BaseModel): + assert isinstance(value, type_) + assert assert_matches_model(type_, cast(Any, value), path=path) + elif inspect.isclass(origin) and origin.__name__ == "HttpxBinaryResponseContent": + assert value.__class__.__name__ == "HttpxBinaryResponseContent" + else: + assert None, f"Unhandled field type: {type_}" + + +def _assert_list_type(type_: type[object], value: object) -> None: + assert is_list(value) + + inner_type = get_args(type_)[0] + for entry in value: + assert_type(inner_type, entry) # type: ignore + + +@contextlib.contextmanager +def update_env(**new_env: str | Omit) -> Iterator[None]: + old = os.environ.copy() + + try: + for name, value in new_env.items(): + if isinstance(value, Omit): + os.environ.pop(name, None) + else: + os.environ[name] = value + + yield None + finally: + os.environ.clear() + os.environ.update(old)